c# - WPF 数据绑定(bind)架构问题

标签 c# wpf xaml dependency-properties datacontext

我正在努力学习如何使用 WPF 绑定(bind)和 MVVM 架构。我在依赖属性方面遇到了一些麻烦。我试图通过将项目绑定(bind)到 DataContext 中的 DependencyProperty 来控制项目在 View 上的可见性,但它不起作用。无论我在下面的 View 模型的构造函数中将 GridVisible 值设置为什么,当我运行代码时它始终显示为可见。

谁能看出我哪里出错了?

C# 代码(ViewModel):

public class MyViewModel : DependencyObject
{
    public MyViewModel ()
    {
        GridVisible = false;
    }

    public static readonly DependencyProperty GridVisibleProperty =
    DependencyProperty.Register(
        "GridVisible",
        typeof(bool),
        typeof(MyViewModel),
        new PropertyMetadata(false,
                new PropertyChangedCallback(GridVisibleChangedCallback)));

    public bool GridVisible
    {
        get { return (bool)GetValue(GridVisibleProperty); }
        set { SetValue(GridVisibleProperty, value); }
    }

    protected static void GridVisibleChangedCallback(
        DependencyObject source,
        DependencyPropertyChangedEventArgs e)
    {
        // Do other stuff in response to the data change.
    }
}

XAML 代码( View ):

<UserControl ... >

    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="BoolToVisConverter" />
    </UserControl.Resources>

    <UserControl.DataContext>
        <local:MyViewModel x:Name="myViewModel" />
    </UserControl.DataContext>

    <Grid x:Name="_myGrid"
        Visibility="{Binding Path=GridVisible,
            ElementName=myViewModel,
            Converter={StaticResource BoolToVisConverter}}">

        <!-- Other elements in here -->

    </Grid>

</UserControl>

我看过几个在线教程,似乎我正确地遵循了我在那里找到的内容。有任何想法吗?谢谢!

最佳答案

从您的绑定(bind)中删除 ElementName,这似乎不正确。 将其更改为:

<Grid x:Name="_myGrid"
        Visibility="{Binding Path=GridVisible,
            Converter={StaticResource BoolToVisConverter}}">

关于c# - WPF 数据绑定(bind)架构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5837569/

相关文章:

c# - 读取 XML 时忽略空格

c# - 在 RDLC 报告中格式化空时间

c# - 当值更改时 WPF 组合框不会更新

wpf - 强制 WPF 组件在引发事件时进行验证

wpf - 没有 .xaml.cs 代码的 XAML 文件

xaml - 如何设置 TextColor Xamarin.Forms TableSection?

c# - 有没有办法按事件触发数据湖分析作业?

c# - 焦点抽象

c# - 将 StackPanel 绑定(bind)到添加子元素的方法

c# - 将按钮插入富文本 block