如何在UWP项目中使用MVVM避免空值
本文关键字:MVVM 空值 UWP 项目 | 更新日期: 2023-09-27 18:16:05
我想添加新的咖啡细节,当我添加使用Addcommand
(自定义命令),但当添加新的细节是null
,那么我如何避免这个问题?
模型等级Coffee
public class Coffee : BindableBase
{
private int coffeeId;
private string coffeeName;
public int CoffeeId
{
get
{
return coffeeId;
}
set
{
coffeeId = value;
RaisePropertyChanged("CoffeeId");
}
}
public string CoffeeName
{
get
{
return coffeeName;
}
set
{
coffeeName = value;
RaisePropertyChanged("CoffeeName");
}
}
}
查看CoffeeAdd.xaml
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Coffee Id"/>
<TextBox Width="120" Height="30" Margin="50 0 0 0" Text="{Binding CoffeeId}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0 20 0 0">
<TextBlock Text="Coffee Name"/>
<TextBox Width="120" Height="30" Margin="20 0 0 0" Text="{Binding CoffeeName}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0 20 0 0">
<Button Content="Add" Width="120" Height="30" Command="{Binding AddCommand}"/>
<Button Content="View" Width="120" Height="30" Margin="20 0 0 0"/>
</StackPanel>
</StackPanel>
ViewModel CoffeeAddViewModel
public class CoffeeAddViewModel:BindableBase
{
private ICoffeeDataService coffeedataservice;
public CoffeeAddViewModel(ICoffeeDataService dataservice)
{
coffeedataservice = dataservice;
LoadCommand();
}
private int _coffeeId;
private string _coffeeName;
public int CoffeeId
{
get
{
return _coffeeId;
}
set
{
_coffeeId = value;
RaisePropertyChanged("CoffeeId");
}
}
public string CoffeeName
{
get
{
return _coffeeName;
}
set
{
_coffeeName = value;
RaisePropertyChanged("CoffeeName");
}
}
public ICommand AddCommand { get; set; }
private void LoadCommand()
{
AddCommand = new CustomCommand(add, canadd);
}
private async void add(object obj)
{
coffeedataservice.AddCoffee(new Model.Coffee { CoffeeId = _coffeeId, CoffeeName = _coffeeName });
var dialog = new MessageDialog("Successfully Added");
await dialog.ShowAsync();
}
private bool canadd(object obj)
{
return true;
}
}
用户输入没有反映在ViewModel
中是因为您只设置了OneWay
绑定。
{Binding CoffeeId}
这个默认语法提供的是OneWay
—从ViewModel
到View
,换句话说,ViewModel
中的属性变化反映在View
中,而不是相反。
要以两种方式启用数据绑定,需要将CoffeeId
和CoffeeName
属性的绑定模式都设置为TwoWay
:
{Binding CoffeeId, Mode=TwoWay}
你的XAML应该是这样的:
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Coffee Id"/>
<TextBox Width="120" Height="30" Margin="50 0 0 0"
Text="{Binding CoffeeId, Mode=TwoWay}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0 20 0 0">
<TextBlock Text="Coffee Name"/>
<TextBox Width="120" Height="30" Margin="20 0 0 0"
Text="{Binding CoffeeName, Mode=TwoWay}"/>
</StackPanel>
<StackPanel Orientation="Horizontal" Margin="0 20 0 0">
<Button Content="Add" Width="120" Height="30" Command="{Binding AddCommand}"/>
<Button Content="View" Width="120" Height="30" Margin="20 0 0 0"/>
</StackPanel>
</StackPanel>