重用WPF DataTemplate

rah*_*hul 0 c# data-binding wpf listbox datatemplate

我有一个ListBox需要显示每个Item的复选框/文本块组合.但是这些项不在集合中,而是在类中作为属性(boolean/String)公开.这意味着我无法在Item的DataTemplate中设置Binding属性,因为每个Item都将绑定到不同的属性.

是否可以定义未绑定到任何属性的DataTemplate,然后在使用DataTemplate时定义Binding.

在伪代码中:

<DataTemplate x:Key="ReusableDataTemplate">
    <StackPanel Orientation="Horizontal">
        <CheckBox />
        <TextBlock />
    </StackPanel>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

后来用它作为:

<ListBox>
  <ListBoxItem DataTemplate="ReusableDataTemplate" CheckBoxBinding="{Path=Enable1}" TextBlockBinding="{Path=Enable1Text}"/>
  <ListBoxItem DataTemplate="ReusableDataTemplate" CheckBoxBinding="{Path=Enable2}" 
TextBlockBinding="{Path=Enable2Text}"/>
  <ListBoxItem DataTemplate="ReusableDataTemplate" CheckBoxBinding="{Path=Enable3}" TextBlockBinding="{Path=Enable3Text}"/>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

H.B*_*.B. 5

这是UserControls为了什么.