我有一个MainWindow,其中包含2个用户控件:“就绪”和“欢迎”。我想显示其中一个,具体取决于视图模型中的枚举值。
应用程序启动时,只有“欢迎”显示,但同时显示了两个部分。在调试中,我看到正在调用ShowWelcome属性值,但从未调用ShowReady,就好像它没有绑定。
即使视图模型的ShowReady属性设置为false,我也不明白为什么仍然显示Ready用户控件。
MainWindow.xaml:
<Window x:Class="xyz.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:xyz.Views"
mc:Ignorable="d"
Title="app" Icon="/Assets/images/wcC.png"
Height="800" Width="240" ResizeMode="NoResize"
Loaded="Window_Loaded">
<StackPanel Orientation="Vertical">
<StackPanel.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVisConverter" />
</StackPanel.Resources>
<local:Ready x:Name="ucReady" Visibility="{Binding ShowReady, Converter={StaticResource BoolToVisConverter}}" />
<local:Welcome x:Name="ucWelcome" Visibility="{Binding ShowWelcome, Converter={StaticResource BoolToVisConverter}}" />
</StackPanel>
</Window>
MainWindow.xaml.cs
namespace xyz.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
//ServerApiCaller api;
ConfigModelApp configApp;
MainWindowVM vm;
public MainWindow(IOptionsMonitor<ConfigModelApp> configApp, ServerApiCaller api)
{
this.configApp = configApp.CurrentValue;
vm = new MainWindowVM();
DataContext = vm;
InitializeComponent();
}
void Window_Loaded(object sender, RoutedEventArgs e)
{
vm.UpdateWindowContext(this.configApp.UserId);
}
internal void UpdateWindowContext(ConfigModelApp newConfig)
{
configApp = newConfig;
vm.UpdateWindowContext(newConfig.UserId);
}
}
}
MainWindowVM.cs
namespace xyz.ViewModels
{
public enum MainWindowContextEnum
{
Unknown,
Welcome,
Ready,
Drafting,
Playing,
}
public class MainWindowVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public MainWindowContextEnum MainWindowContext { get; set; } = MainWindowContextEnum.Welcome;
public bool ShowWelcome => MainWindowContext == MainWindowContextEnum.Welcome;
public bool ShowReady => MainWindowContext == MainWindowContextEnum.Ready;
public void UpdateWindowContext(string userId)
{
MainWindowContext = Guid.TryParse(userId, out Guid g) ? MainWindowContextEnum.Ready : MainWindowContextEnum.Welcome;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ShowReady)));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(ShowWelcome)));
}
}
}
答案 0 :(得分:2)
如果db.collection.find().sort({"status.date":-1})
有效,则您正在显式设置Visibility="{Binding DataContext.ShowReady, RelativeSource={RelativeSource AncestorType=Window}, Converter={StaticResource BoolToVisConverter}}"
中的DataContext
。
您不应这样做,因为这意味着Ready
将不再从定义了UserControl
属性的窗口中继承其DataContext
。这就是绑定失败的原因。
ShowReady
通常应该继承其UserControl
。