为什么 WPF 窗口.可见性绑定必须具有 Mode=TwoWay 才能调用属性
本文关键字:TwoWay Mode 属性 调用 窗口 WPF 可见性 绑定 为什么 | 更新日期: 2023-09-27 18:30:38
ViewModel:
public FloatingToolbarWindowViewModel(GuiItems guiItems)
{
GuiItemsInstance = guiItems;
GuiItemsInstance.Host = Host;
GuiItemsInstance.RefreshVisibility = RefreshVisibility;
}
private Visibility _windowVisibility;
public Visibility WindowVisibility
{
get { return _windowVisibility; }
set
{
//raises PropertyChanged-event
SetValue(ref _windowVisibility, value);
}
}
// this check if any of the toolbars should be in a window and then sets visibility
public void RefreshVisibility(int RoleId)
{
if (GuiItemsInstance.ToolbarItems.Any(i => i.ToolbarLocation == ToolbarLocation.Float && i.RoleId == RoleId))
WindowVisibility = Visibility.Visible;
else
WindowVisibility = Visibility.Hidden;
}
XAML:
Visibility="{Binding WindowVisibility, Mode=TwoWay}"
这意味着它永远无法工作,因为最终 ShowWindow 会将属性更新为可见,即使初始化已经"决定"它应该被隐藏。
所以我所做的是文件背后的代码中的黑客:
public partial class FloatingToolbarWindow : Window
{
public FloatingToolbarWindow()
{
InitializeComponent();
ContentRendered += FloatingToolbarWindow_ContentRendered;
}
private void FloatingToolbarWindow_ContentRendered(object sender, EventArgs e)
{
((FloatingToolbarWindowViewModel)DataContext).RefreshWindowVisibility();
}
视图模型额外的黑客方法:
public void RefreshVisibility()
{
RefreshVisibility(GuiItemsInstance.ActiveRoleId);
}
有没有办法在没有这种可怕的黑客的情况下做到这一点。此外,这不应该首先与 Mode=OneWay 绑定一起使用吗?
我会让 WindowVisibility 成为只读属性:
public Visibility WindowVisibility
{
get
{
if (GuiItemsInstance.ToolbarItems.Any(i => i.ToolbarLocation == ToolbarLocation.Float && i.RoleId == RoleId))
return Visibility.Visible;
else
return Visibility.Hidden;
}
}
绑定可见性单向:
Visibility="{Binding WindowVisibility, Mode=OneWay}"
然后,每当您必须"更新"可见性时,只需提高属性更改即可......我不知道你在用什么,也可以
OnPropertyChanged("WindowVisibility");
或
OnPropertyChanged(() => WindowVisibility);