How to bind property name to which column is binded to pass as command parameter

*爱你&永不变心* 提交于 2019-12-06 14:01:03

问题


On each DataGridColumnHeader I have a button that I use to open a popup. As a parameter it sends the column's bound Property name to the ICommand in my ViewModel.

This works well for any DataGridTextColumn however when it comes to a DataGridComboBoxColumn the structure is different.

How would I solve this?

<Button Command="{Binding DataContext.OpenFilterCommand, 
                  RelativeSource={RelativeSource AncestorType=UserControl}}"
        CommandParameter="{Binding Column.Binding.Path.Path, 
                  RelativeSource={RelativeSource Mode=TemplatedParent}}"/>

Problem Column Definition

<DataGridComboBoxColumn Header="Company" >
    <DataGridComboBoxColumn.ElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.CompanyCollection}"/>
            <Setter Property="IsReadOnly" Value="True"/>
            <Setter Property="SelectedValue" Value="{Binding Company}"/>
        </Style>
    </DataGridComboBoxColumn.ElementStyle>
    <DataGridComboBoxColumn.EditingElementStyle>
        <Style TargetType="ComboBox">
            <Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}, Path=DataContext.CompanyCollection}"/>
            <Setter Property="SelectedValue" Value="{Binding Company}"/>
        </Style>
    </DataGridComboBoxColumn.EditingElementStyle>
</DataGridComboBoxColumn>

回答1:


Like I mentioned in previous question here that how to get value for DataGridTextColumn where i suggested to use Column.Binding.Path.Path to get bound property name.

But that won't work in this case since DataGridComboBoxColumn does not have any binding property. If syntax is like the one you mentioned in question above, you can get like this:

For SelectedValue i.e. Company:

<Button Command="{Binding DataContext.OpenFilterCommand, 
                  RelativeSource={RelativeSource AncestorType=UserControl}}"
        CommandParameter="{Binding 
                   Column.EditingElementStyle.Setters[1].Value.Path.Path, 
                  RelativeSource={RelativeSource Mode=TemplatedParent}}"/>

EXPLANATION

TemplatedParent (DataGridColumnHeader) --> Column (DataGridComboBoxColumn) --> EditingElementStyle(EditingElementStyle) --> Setters(1) (get first setter from style) --> Value (Setter Value) --> Path (PropertyPath) --> Path (Actual PropertyName)

If you want to get ItemsSource property name, replace Setters[1] with Setters[0].



来源:https://stackoverflow.com/questions/22804196/how-to-bind-property-name-to-which-column-is-binded-to-pass-as-command-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!