我有两个的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