1.注册Dialog对应信息
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterDialog< Views.DialongView,ViewModels.DialongViewModel>();//viewModel一定要继承 IDialogAware
}
2.调用
private IDialogService _dialogService;//通过IDialogService接口获取当全局定义可用区域,往这个区域动态的去设置内容.
public MainViewModel( IDialogService dialogService)
{//构造函数获取IDialogService接口获取当全局定义可用区域
_dialogService = dialogService;
}
//下面是使用
private void Open_Dialog(object obj)
{
//obj要各View中的窗体一个名字
DialogParameters par = new DialogParameters();
par.Add("Title", "测试弹窗");
par.Add("Message", "生是中国人,死是中国魂.");//传两个参数过去
par.Add("Brush", Brushes.Red); //加个字体颜色
_dialogService.ShowDialog(obj.ToString(), par, callback=>
{
if (callback.Result == ButtonResult.OK)
{//点击了确定按键
string result = callback.Parameters.GetValue<string>("Value");
}
else
{
//点击了取消
}
});
}
3.dialog ViewModel接收处理以及返回
public class DialongViewModel : BindableBase, IDialogAware//Dialog窗体一定要继承这个IDialogAware接口
{
private string messagem;
public string Message
{
get { return messagem; }
set { messagem = value; RaisePropertyChanged(); }
}
private Brush brushChange;
public Brush BrushChange
{
get { return brushChange; }
set { brushChange = value; RaisePropertyChanged(); }
}
public string Title { get; set; }
public event Action<IDialogResult> RequestClose;
/// <summary>
/// 系统的那个Close可用
/// </summary>
/// <returns></returns>
public bool CanCloseDialog()
{
return true;
}
/// <summary>
/// 关掉窗体的事件
/// </summary>
public void OnDialogClosed()
{
DialogParameters parameters = new DialogParameters();
parameters.Add("Value", "Click Confirm");
RequestClose?.Invoke(new DialogResult(ButtonResult.OK, parameters));
}
/// <summary>
/// 打开窗体的事件
/// </summary>
/// <param name="parameters"></param>
public void OnDialogOpened(IDialogParameters parameters)
{
Title = parameters.GetValue<string>("Title");//窗体显示的标题
Message = parameters.GetValue<string>("Message");//窗体显示的内容
BrushChange= parameters.GetValue<Brush>("Brush"); //字显示的颜色
}
public ICommand ClickCommandDialogOk //绑定的OK按键
{
get => new DelegateCommand(OnDialogClosed);
}
public ICommand ClickCommandDialogCancel //绑定的取消按键
{
get => new DelegateCommand(() =>
{
RequestClose?.Invoke(new DialogResult(ButtonResult.No));
});
}
}
UI绑定代码
<Grid Background="White">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="auto "></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Message}" Foreground="{Binding BrushChange}" FontSize="20" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="15"></TextBlock>
<StackPanel Grid.Row="2" HorizontalAlignment="Right" Orientation="Horizontal" >
<Button Content="取消" Margin="10" Command="{Binding ClickCommandDialogCancel}" FontSize="20"></Button>
<Button Content="确定" Margin="10" Command="{Binding ClickCommandDialogOk }" FontSize="20"></Button>
</StackPanel>
</Grid>
资源