【发布时间】:2011-08-15 19:20:10
【问题描述】:
我正在尝试学习如何使用 WPF 绑定和 MVVM 架构。我在依赖属性方面遇到了一些麻烦。我试图通过将项目绑定到 DataContext 中的 DependencyProperty 来控制视图上项目的可见性,但它不起作用。无论我在下面视图模型的构造函数中将GridVisible 值设置为什么,在我运行代码时它始终显示为可见。
谁能看出我哪里出错了?
C# 代码(视图模型):
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 代码(查看):
<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>
我查看了一些在线教程,似乎我正确地遵循了我在那里找到的内容。有任何想法吗?谢谢!
【问题讨论】:
标签: c# wpf xaml dependency-properties datacontext