Combobox binding in Datatemplate

后端 未结 2 1026
执笔经年
执笔经年 2021-01-26 03:40

Hi i am actually creating a WPF DataGrid Custom Control. What is want this combobos should show the genders in the combobox and what is heppening when i am keeping the combobox

相关标签:
2条回答
  • 2021-01-26 04:05

    If you are inside a DataTemplate the DataContext will be the object that is being templated. So your binding, which is relative to the DataContext if only a binding path is specified will not find the ItemsSource.

    Normally you can use a RelativeSource-binding to find the control which still has the DataContext in which your ItemsSource can be found. (See RV1987's answer; i thought it did not work earlier because if you have a DataGridComboBoxColumn the very same RelativeSource-ItemsSource-binding will not work, that is because a column on its own is abstract and does not appear in the trees unlike the control that is created by a template)

    Since the DataContext of the UserControl should be what you are looking for you can name your UserControl (control for example) and bind like this:

    ItemsSource="{Binding Source={x:Reference control}, Path=DataContext.Genders}"
    

    (Note that x:Reference is quite new, it does not exist in .NET 3.5, using ElementName=control instead will not work)

    0 讨论(0)
  • 2021-01-26 04:09

    Try using this in your datatemplate -

    <ComboBox x:Name="c1" ItemsSource="{Binding DataContext.Genders, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" DisplayMemberPath="Id"  Height="50" Width="100"></ComboBox>
    

    This will find the property Genders in the datacontext of your usercontrol which is DataSource.

    0 讨论(0)
提交回复
热议问题