【问题标题】:WPF DataTemplate and BindingWPF 数据模板和绑定
【发布时间】:2010-09-23 17:15:31
【问题描述】:

我正在对列表框的项目源进行数据模板化以显示标签和组合框。在数据模板中,我为组合框分配了一个新的 itemssource,但无法使其正常工作。

或者理想情况下,如何将数据模板中的组合框绑定到不同的源。

谢谢。玛尼

用户控制:

<DockPanel>
        <ListBox x:Name="lstBox" ItemsSource="{Binding FilterControls}" />
</DockPanel>

 <!--DataTemplate For SearchElement Type-->
<DataTemplate DataType="{x:Type CustomTypes:FilterElement}">
  <Label> Text </Label>
  *<ComboBox  ItemsSource="{Binding Employees}"DisplayMemberPath="Sex" />*
</DataTemplate>

视图模型:

List<FilterElement> FilterControls;
List<Employee> Employees

Class FilterElement 
{
string Caption;
}

class Employee
{
string Sex;
}

【问题讨论】:

    标签: wpf wpf-controls binding


    【解决方案1】:

    在您的组合框中,您将绑定到当前数据上下文中的 Employees,这将是一个 FilterElement 对象 - 没有可绑定的员工属性。

    在您的绑定中,您可能希望将 Source= 设置为其他内容,这会覆盖您的数据上下文

    有很多方法可以设置这个简单的方法来做到这一点(很容易放在这里,无论如何)将collectionViewSource添加到你的窗口/控件的资源(我放了Whatever.Resources - 它可以进入几乎任何包含元素)

    <Whatever.Resources>
      <CollectionViewSource x:Key="employeeSource" Source="{Binding Employees}">
    </Whatever.Resources>
    

    然后在你的数据模板中

    <ComboBox ItemsSource={Binding Source={StaticResource employeeSource}}" ... />
    

    请注意,使用 CollectionViewSource 也可以让您在 xaml 中进行排序/分组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-23
      • 2021-12-25
      • 2014-08-23
      • 1970-01-01
      • 2012-01-22
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      相关资源
      最近更新 更多