我有兩個的ViewModels:綁定可見性,以不同的源比的DataContext
public class CommandViewModel
{
public string DisplayName { get; set; }
public ICommand Command { get; set; }
}
和
public class SomeViewModel : INotifyPropertyChanged
{
private bool someFlag;
private CommandViewModel someCommand;
public bool SomeFlag
{
get
{
return someFlag;
}
set
{
if (value == someFlag)
return;
someFlag = value;
OnPropertyChanged("SomeFlag");
}
}
public CommandViewModel SomeCommandViewModel
{
get
{
if (someCommand == null)
{
someCommand = new CommandViewModel();
// TODO: actually set the DisplayName and Command
}
return someCommand;
}
}
}
而且我有兩個相應的視圖:
<UserControl x:Class="ButtonView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="28" d:DesignWidth="91">
<Button Content="{Binding Path=DisplayName}" Command="{Binding Path=Command}" />
</UserControl>
和
<UserControl x:Class="SomeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d" Height="125" Width="293" />
<ViewButton
Visibility="{Binding Path=SomeFlag, Converter={StaticResource BoolToVisibilityConverter}}"
DataContext="{Binding Path=SomeCommandViewModel}" />
</UserControl>
我在綁定DataContext時遇到了ButtonView的可見性綁定問題。如果我離開DataContext,Visibility工作得很好(當SomeFlag切換值時,按鈕的可見性隨之改變) - 但顯示文本和命令不起作用。如果我綁定DataContext,顯示文本和命令工作,但可見性不。我確信它與我將DataContext綁定到SomeCommandViewModel時的事實有關,它期望其中存在「SomeFlag」。當然,事實並非如此。
我是WPF/MVVM n00b。什麼是更好的設計? – fre0n 2010-08-23 18:53:20