【问题标题】:WPF how to retrieve binded property in code behindWPF如何在后面的代码中检索绑定属性
【发布时间】:2020-06-14 23:49:25
【问题描述】:

在我的遗留项目中,我需要通过后面的代码获取绑定属性名称。 XAML:

<DataGridTextColumn MinWidth="180" MaxWidth="180" Width="Auto" Binding="{Binding ConfigObject.MAC_Descr}" Header="Descr" Foreground="Black">
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="TextBlock">
            <Setter Property="Padding" Value="6,12" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsDirty}" Value="True">
                    <Setter Property="TextBlock.Background" Value="{StaticResource IsDirtyColor}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGridTextColumn.ElementStyle>
    <DataGridTextColumn.EditingElementStyle>
        <Style TargetType="TextBox">
            <Setter Property="Background" Value="White"/>
            <Setter Property="Padding" Value="5,12"/>
            <Setter Property="BorderThickness" Value="0"/>
        </Style>
    </DataGridTextColumn.EditingElementStyle>
</DataGridTextColumn>

我使用的事件:

private void Row_DoubleClick(object sender, MouseButtonEventArgs e)
{
    if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
    {
        DataGridCell row = sender as DataGridCell;
        if (row == null) return;

        // Binding column name??
        string bindingExpression = row.GetBindingExpression(TextBlock.TextProperty).ResolvedSourcePropertyName;
    }
}

基本上在上述情况下,我需要检索“MAC_Descr”。有什么帮助吗?

【问题讨论】:

    标签: wpf binding datagrid


    【解决方案1】:

    你可以试试这样的:

    private void OnCellDoubleClick(object sender, MouseButtonEventArgs e)
    {
        if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl))
        {
            if (!(sender is DataGridCell cell)) return;
            if (!(cell.Column is DataGridTextColumn column)) return;
            if (!(column.Binding is Binding binding)) return;
    
            var path = binding.Path.Path;
        }            
    }
    

    【讨论】:

    • 好吧,我已经检索了 dataContext,但是由于我有几个具有不同绑定属性的列,所以我基本上需要获取属性的名称,在上面的例子中,MAC_Desc
    • 好的,所以你只需要属性的name。我没有从你的问题中得到具体的答案。
    • 更新了答案。
    【解决方案2】:

    将单元格的Content 转换为TextBoxTextBlock,具体取决于单元格是否可编辑:

    DataGridCell row = sender as DataGridCell;
    if (row == null) return;
    
    TextBox textBox = row.Content as TextBox;
    if (textBox == null) return;
    
    string bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty)
        .ResolvedSourcePropertyName;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      • 2015-11-07
      • 1970-01-01
      • 1970-01-01
      • 2011-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多