我正在努力学习如何使用 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/