WPF如何在代码隐藏中检索绑定的属性



在我的遗留项目中,我需要通过代码隐藏获得绑定属性名称。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"。有什么帮助吗?

你可以试试这样的东西:

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;
}            
}

根据单元格是否可编辑,将单元格的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;

最新更新