C# 设计时空引用错误
在我的WPF应用程序中,我使用C# 设计时空引用错误,c#,wpf,xaml,C#,Wpf,Xaml,在我的WPF应用程序中,我使用 {Binding Source={x:Reference myComboBox} ,Path=SelectedItem} 我在DataGrid列中执行此操作 这是在设计时(不是运行时)引发空引用异常。有没有办法解决这个问题,或者我可以通过其他方式访问所选项目 组合框: <ComboBox x:Name="myComboBox" ItemsSource="{Binding MyItems}"
{Binding Source={x:Reference myComboBox} ,Path=SelectedItem}
我在DataGrid列中执行此操作
这是在设计时(不是运行时)引发空引用异常。有没有办法解决这个问题,或者我可以通过其他方式访问所选项目
组合框:
<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}" />
为什么不试试
{Binding ElementName=myComboBox,Path=SelectedItem}
在本例中,请尝试使用继承数据上下文的Freezable类型。现在我们不需要参考组合框
,因为我们将在数据上下文
中有一个属性。我认为,这是一个更普遍的解决方案:
绑定代理
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));
}
<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>
XAML
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));
}
<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>
你能发布完整的代码吗?@NullReferenceException我希望这足够了。你使用的是什么版本的VisaulStudio
?2013 Premium with Update 1如果我没有弄错的话,它将不起作用,因为DataGridColumns
不在DataGrid
的可视化树中。