WPF:如何将Visibility属性绑定到xaml元素?

时间:2013-09-30 09:23:54

标签: c# wpf xaml binding viewmodel

我遇到了一些需要帮助的问题。我想将视图模型中的可见性属性绑定到xaml元素,这样我只需更改viewmodel中的值就可以进行一些直观的更改(在这种情况下可以折叠或显示)。

我得到了这个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中的属性 UiWelcomeVisibility UiBackendVisibility 。这些属性现在定义如下:

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;
    }

ViewModel:

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;
    }
}

我只是没有看到任何编码错误(事实上我没有在运行时获得)但是Ueodel的UiBackendVisibility不会改变BackendUI-visibility-property。

有什么想法吗?谢谢到目前为止。

1 个答案:

答案 0 :(得分:1)

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

  1. 首先没有名为“UiWelcomeVisibility”的元素。
  2. 即使存在,视觉元素本身也不是Visibility属性的有效值。
  3. 你想要的是数据绑定到viewmodel。假设您已将DataContext设置为viewmodel,只需使用

    即可
    <welcome:WelcomeScreen ... Visibility="{Binding UiWelcomeVisibility}" />