Rob*_*erd 5 c# wpf datacontext xaml dependency-properties
我正在尝试学习如何使用WPF绑定和MVVM架构.我在Dependency Properties遇到了一些麻烦.我试图通过将它绑定到DataContext中的DependencyProperty来控制视图上项目的可见性,但它不起作用.无论我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.
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我在线查看了几个教程,看起来我正确地遵循了我在那里发现的内容.有任何想法吗?谢谢!
将 ElementName 从绑定中删除,这似乎不正确。将其更改为:
<Grid x:Name="_myGrid"
Visibility="{Binding Path=GridVisible,
Converter={StaticResource BoolToVisConverter}}">
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
342 次 |
| 最近记录: |