in my WPF application I refer to a selected value of a combobox with
{Binding Source={x:Reference myComboBox} ,Path=SelectedItem}
I do this inside of DataGrid Columns.
This is throwing a null reference exception at design time (not run time). Is there any way to fix this, or can I access the selected Item somehow other than that?
ComboBox:
<ComboBox x:Name="myComboBox"
ItemsSource="{Binding MyItems}"
DisplayMemberPath="Name"
SelectedItem="{Binding SelectedItem}"
/>
DataGridTextColumn:
<DataGridTextColumn HeaderStyle="{DynamicResource myStyle}" Visibility="{Binding Source={x:Reference myComboBox} ,Path=SelectedItem, Converter={StaticResource ConvertSomething}, ConverterParameter={StaticResource Something}}" Header="MyHeader " Width="*" Binding="{Binding Path=MyBindingName}" />
In this case try using proxy
of Freezable type, that inherit DataContext
. Now we do not need to refer to ComboBox
because we will have a property that is in DataContext
. I think, this is a more universal solution:
BindingProxy
public class BindingProxy : Freezable
{
#region Overrides of Freezable
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
#endregion
public object Data
{
get
{
return (object)GetValue(DataProperty);
}
set
{
SetValue(DataProperty, value);
}
}
public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data",
typeof(object),
typeof(BindingProxy));
}
XAML
<DataGrid>
<DataGrid.Resources>
<local:BindingProxy x:Key="bindingProxy" Data="{Binding}" />
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Visibility="{Binding Path=MySelectedItem,
Converter={StaticResource ConvertSomething},
ConverterParameter={StaticResource Something}}"
Source={StaticResource bindingProxy}}" />
</DataGrid.Columns>
</DataGrid>
为什么不试试{Binding ElementName=myComboBox ,Path=SelectedItem}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.