我在學習如何使用WPF綁定和MVVM體系結構。我遇到了依賴屬性的一些麻煩。我試圖通過將它綁定到DataContext中的DependencyProperty來控制視圖上項目的可見性,但它不起作用。無論我如何在下面的視圖模型的構造函數中設置GridVisible
值,在運行代碼時它總是顯示爲可見。WPF數據綁定體系結構問題
任何人都可以看到我要去哪裏錯了嗎?
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>
我在幾個教程在網上看了,似乎像我正確地遵循我在那裏找到的內容。有任何想法嗎?謝謝!
其實我把你的代碼複製出來,發現它與包含和不包含ElementName的綁定一起工作。你在使用usercontrol(即一個窗口或其他用戶控件)?也許在那裏有什麼問題(你沒有包含代碼)。 – thornhill 2011-04-29 21:51:28
我刪除了ElementName,它仍然不起作用。看起來你是對的 - 它可能與我的代碼的另一部分有關,而不是上面發佈的消毒版本。不幸的是,我不能發佈實際的代碼,因爲它是爲了工作。 – RobotNerd 2011-04-29 21:55:34
在這種情況下,當您運行應用程序並打開包含此用戶控件的窗口時,請在VisualStudio的「輸出」窗口中查找與此文本類似的任何錯誤。 「BindingExpression path error:'GridVisible'property not found on 'object ......「 該消息的內容可能會幫助您進一步調試。 抱歉,我無法幫助你更多。祝你好運。 – thornhill 2011-04-30 08:06:54