0

我有一些问题需要帮助。我想将视图模型中的可见性属性绑定到 xaml 元素,因此我只需更改视图模型中的值即可获得一些视觉上的更改(在本例中为折叠或显示)。

我得到了这个 xaml

<Window x:Class="PampelMuse.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:welcome="clr-namespace:PampelMuse.Views.Welcome"
    xmlns:backend="clr-namespace:PampelMuse.Views.Backend"
    xmlns:pampelMuse="clr-namespace:PampelMuse" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    Title="PampelMuse" Height="670" Width="864">
<Grid>
    <Image HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Source="Resources/Images/Backgrounds/4.jpg" Stretch="UniformToFill" />
    <welcome:WelcomeScreen x:Name="UIWelcome" HorizontalAlignment="Center" VerticalAlignment="Center" Visibility="{Binding ElementName=UiWelcomeVisibility}" />
    <backend:BackendUI x:Name="UIBackend" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Visibility="{Binding ElementName=UiBackendVisibility}" />
</Grid>

如您所见,可见性绑定到UIModel 中的UiWelcomeVisibilityUiBackendVisibility属性。这些属性现在定义如下:

public partial class MainWindow : Window
{
    private ViewModel.ViewModel ViewModel = PampelMuse.ViewModel.ViewModel.GetInstance();

    public MainWindow()
    {
        InitializeComponent();

        DataContext = ViewModel; // Setting the data context what effects all the xaml elements in this component too, including UIWelcome and BackendUI

        ViewModel.UIModel.UiBackendVisibility = Visibility.Collapsed;
    }

视图模型:

public class ViewModel
{
    private static ViewModel instance = new ViewModel();
    public UIModel UIModel = UIModel.GetInstance();

    public static ViewModel GetInstance()
    {
        return instance;
    }
}

和 UIModel:

public class UIModel
{
    private static UIModel instance = new UIModel();

    public Visibility UiWelcomeVisibility { get; set; }
    public Visibility UiBackendVisibility { get; set; }

    public static UIModel GetInstance()
    {
        return instance;
    }
}

我只是在这里看不到任何编码错误(实际上我在运行时也没有看到),但是 UIModel 的 UiBackendVisibility 并没有改变 BackendUI-visibility-property。

有任何想法吗?感谢到目前为止。

4

1 回答 1

1

你做错了绑定。Visibility="{Binding ElementName=UiWelcomeVisibility}"将元素的可见性设置为等于另一个名为“UiWelcomeVisibility”的可视元素。这有两个问题:

  1. 首先没有名为“UiWelcomeVisibility”的元素。
  2. 即使存在,视觉元素本身也不是属性的有效值Visibility

您想要的是数据绑定到视图模型。假设您已经将 设置DataContext为视图模型,只需使用

<welcome:WelcomeScreen ... Visibility="{Binding UiWelcomeVisibility}" />
于 2013-09-30T09:28:27.427 回答