1.关于前端元素绑定视图模型时,视图模型属性更新时刷新前端
总述:在视图模型中更新源时,必须更新属性,而不能更新字段,因为更新字段并不会触发PropertyChanged事件,从而导致前端元素值不能被更新.
示例
前端
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:viewModel="clr-namespace:UIL.ViewModel.UserMgt"
<Page.DataContext>
<viewModel:UserMgtVM />
</Page.DataContext>
<materialDesign:DialogHost IsOpen="{Binding IsOpen}">
<materialDesign:DialogHost.DialogContent>
<Frame NavigationUIVisibility="Hidden"
Content="{Binding DialogHostContent}"
Height="{Binding DialogHostHeight}"
Width="{Binding DialogHostWidth }" />
</materialDesign:DialogHost.DialogContent>
</materialDesign:DialogHost>
视图模型
internal class UserMgtVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName]string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private Page _dialogHostContent;
public Page DialogHostContent { get { return _dialogHostContent; } set { _dialogHostContent = value; NotifyPropertyChanged(); } }
private bool _isOpen;
public bool IsOpen { get { return _isOpen; } set { _isOpen = value; NotifyPropertyChanged(); } }
private double _dialogHostHeight;
public double DialogHostHeight { get { return _dialogHostHeight; } set { _dialogHostHeight = value; NotifyPropertyChanged(); } }
private double _dialogHostWidth;
public double DialogHostWidth { get { return _dialogHostWidth; } set { _dialogHostWidth = value; NotifyPropertyChanged(); } }
public ICommand AddUserCmd
{
get
{
return new DelegateCommand()
{
CanExecuteFunc = (obj) => { return true; },
ExecuteAction = (obj) =>
{
DialogHostContent = new AddUserPage();//这个地方不能给_dialogHostContent赋值,因为不会触发PropertyChanged事件。下面3个属性一样。
DialogHostWidth = DialogHostContent.Width;
DialogHostHeight = DialogHostContent.Height;
IsOpen = true;
}
};
}
}
}