我目前正在尝试找到一种方法来检查父属性在绑定到子属性之前是否为null,如下所示:
...{Binding Item.Text}
在访问Item
属性之前,有没有办法检查Text
是否为空?现在,我在NullReferenceException
中得到PresentationFramework.dll
,这会导致应用崩溃。
当我在ViewModel构造函数中设置Item并在渲染步骤开始之前验证它存在时,这一点特别奇怪:
public MyViewModel()
{
Item = new Foo();
Item.Text = "Bar";
}
答案 0 :(得分:0)
我建议为要公开的模型属性创建一个viewmodel属性。
因为你所展示的例子对我有用..
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MyViewModel();
}
}
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Foo item;
public MyViewModel()
{
Item = new Foo();
Item.Item = "Bar";
}
public Foo Item
{
get
{
return this.item;
}
set
{
this.item = value;
RaisePropertyChanged("Item");
}
}
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class Foo
{
public string Item { get; set; }
}
<TextBox Width="200" Height="30" Text="{Binding Item.Item, Mode=TwoWay}" TextAlignment="Center"/>
您可以公开子属性并像这样执行检查..
public class MyViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Foo item;
public MyViewModel()
{
//Item = new Foo();
//Item.Item = "Bar";
}
public Foo Item
{
get
{
return this.item;
}
set
{
this.item = value;
RaisePropertyChanged("Item");
}
}
public string Bar
{
get
{
if(Item == null)
{
return "Item is null. OMG!";
}
else
{
return Item.Item;
}
}
set
{
Item.Item = value;
RaisePropertyChanged("Bar");
}
}
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<TextBox Width="200" Height="30" Text="{Binding Bar}" TextAlignment="Center"/>
有了这个,您可能想要更改视图模型设计。