单视图,多个ViewModels - 避免绑定错误?

时间:2015-11-02 14:58:42

标签: c# wpf mvvm binding

有一个带有许多控件的View(窗口),以简化:

<!-- edit property A -->
<TextBlock Text="A" ... />
<TextBox Text="{Binding Config.A}" ... />
<Button Command={Binding DoSometingWitA} ... />

<!-- edit property B -->
<TextBox Text="{Binding Config.B}" ... />

<!-- edit property C -->
<ComboBox Text="{Binding Config.C}" ... />

此视图用于显示和编辑多个配置:

public class ViewModel: INotifyPropertyChanged
{
    public BaseConfig Config {get {...} set {...}}
}

public class ConfigType1: BaseConfig { ... } // only has A
public class ConfigType2: BaseConfig { ... } // only has B
public class ConfigType3: BaseConfig { ... } // only has C
public class ConfigType4: BaseConfig { ... } // has A and B
public class ConfigType5: BaseConfig { ... } // has A and C
对于某些配置,

属性可能可能不存在。因此存在绑定错误。

问题:有没有办法隐藏控件哪些属性不存在于当前Config对象中(这可以通过反射轻松完成)以及避免出现绑定错误(这是实际问题,我不想在视图中重新发明PropertyGrid,也不想使用一个?

E.g。如果Config = new ConfigType1()(仅具有A属性),则View将仅包含用于编辑属性A的控件,用于编辑属性BC等的控件。应隐藏,不要导致绑定错误。

如果有人愿意使用它,这是一个测试用例。

XAML:

<TextBox Text="{Binding Config.A}" Visibility="Collapsed"/>
<TextBox Text="{Binding Config.B}" Visibility="Hidden"/>
<Button VerticalAlignment="Bottom"
        Content="..."
        Click="Button_Click" />

CS:

public partial class MainWindow : Window
{
    public class BaseConfig { }

    public class ConfigA : BaseConfig
    {
        public string A { get; set; }
    }

    public class ConfigB : BaseConfig
    {
        public string B { get; set; }
    }

    public BaseConfig Config { get; private set; }

    public MainWindow()
    {
        InitializeComponent();
        Config = new ConfigA() { A = "aaa" };
        DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Config = new ConfigB() { B = "bbb" };
        DataContext = null;
        DataContext = this;
    }
}

最初缺少B的绑定错误,点击按钮(ConfigB将被分配后),存在缺少A的绑定错误。

如何避免这些错误?如果属性存在,可以通过反射检查来控制可见性(但是仍然存在如何组织它的问题。)

4 个答案:

答案 0 :(得分:1)

您需要的是DataTemplate。

工作样本:

 public BaseConfig Config { get; set; }
 <Window.Resources>
    <DataTemplate DataType="{x:Type o:ConfigA}">
        <!--
          You can add here any control you wish applicable to ConfigA.
          Say, a textbox can do.  
         -->
        <TextBlock Text="{Binding A}"/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type o:ConfigB}">
        <TextBlock Text="{Binding B}"/>
    </DataTemplate>
    <DataTemplate DataType="{x:Type o:ConfigType10000000000}">
        <superComplicatedControl:UniqueControl ProprietaryProperty="{Binding CustomProperty}"/>
    </DataTemplate>
    <!--  Rachel's point  -->
    <DataTemplate DataType="{x:Type o:Config4}">
        <StackPanel>
           <ContentControl Content="{Binding ConfigA}"/>
           <ContentControl Content="{Binding ConfigB}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>
<Grid>
    <StackPanel>
         <ContentControl Content="{Binding Config}" />
         <Button VerticalAlignment="Bottom" Content="woosh" Click="Button_Click" />
    </StackPanel>
 </Grid>
private void Button_Click(object sender, RoutedEventArgs e)
{
    // Config = new ConfigB() { B = "bbb" };
    Config = new Config4() { ConfigA = (ConfigA) Config, ConfigB = new ConfigB { B = "bbb" } };
    DataContext = null;
    DataContext = this;
}

//…

// Rachel's point
public class Config4 : BaseConfig
{
    public string A4 { get; set; }

    public ConfigA ConfigA { get; set; }
    public ConfigB ConfigB { get; set; } 
}

答案 1 :(得分:1)

在我看来,tagaPdyk的答案是正确的,但我认为样本可以更好地解释如何做。

不需要反思。我们的想法是将implicit DataTemplatesContentPresenter结合起来。

我们假设我们必须使用数据类型:Data1Data2。这是他们的代码:

public class Data1
{
    public string Name { get; set; }
    public string Description { get; set; }
}

public class Data2
{
    public string Alias { get; set; }
    public Color Color { get; set; }
}

现在我创建一个简单的ViewModel:

public class ViewModel : PropertyChangedBase
{
    private Data1 data1 = new Data1();
    private Data2 data2 = new Data2();

    private object current;
    private RelayCommand switchCommand;

    public ViewModel1()
    {
        switchCommand = new RelayCommand(() => Switch());
        Current = data1;
    }

    public ICommand SwitchCommand
    {
        get
        {
            return switchCommand;
        }
    }

    public IEnumerable<Color> Colors
    {
        get
        {
            List<Color> colors = new List<Color>();
            colors.Add(System.Windows.Media.Colors.Red);
            colors.Add(System.Windows.Media.Colors.Yellow);
            colors.Add(System.Windows.Media.Colors.Green);

            return colors;
        }
    }

    private void Switch()
    {
        if (Current is Data1)
        {
            Current = data2;
            return;
        }

        Current = data1;
    }

    public object Current
    {
        get
        {
            return current;
        }
        set
        {
            if (current != value)
            {
                current = value;
                NotifyOfPropertyChange("Current");
            }
        }
    }
}

其中PropertyChangedBaseINotifyPropertyChanged的基本实现类。

现在最重要的 - 对于这个问题 - 部分,即XAML

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <CollectionViewSource x:Key="colors" Source="{Binding Path=Colors, Mode=OneTime}" />

        <DataTemplate DataType="{x:Type local:Data1}">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>

                <TextBlock Text="Name" VerticalAlignment="Center" />
                <TextBox Text="{Binding Name}" Grid.Column="1" Margin="5" />

                <TextBlock Text="Description" Grid.Row="1" VerticalAlignment="Center" />
                <TextBox Text="{Binding Description}" Grid.Column="1" Grid.Row="1" Margin="5" />
            </Grid>
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:Data2}">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>

                <TextBlock Text="Alias" VerticalAlignment="Center" />
                <TextBox Text="{Binding Alias}" Grid.Column="1" Margin="5" />

                <TextBlock Text="Color" Grid.Row="1" VerticalAlignment="Center" />
                <ComboBox Text="{Binding Color}" Grid.Column="1" Grid.Row="1" Margin="5"
                          ItemsSource="{Binding Source={StaticResource colors}}" />
            </Grid>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ContentPresenter Content="{Binding Path=Current}" />
        <Button Content="Switch" Command="{Binding SwitchCommand}" Margin="30" />
    </StackPanel>
</Window>

正如您所看到的,我为DataTemplate中要处理的每个对象定义了ContentPresenter。我必须为每个DataType设置DataTemplate属性。这样,ContentPresenter中将自动使用正确的模板(取决于绑定到其DataContext的对象的类型)。

您可以使用“切换”按钮在Data1对象和Data2对象之间切换。此外,如果您查看VS的输出窗口,您将看不到有关绑定错误的消息。

我希望我的示例可以帮助解决您的问题。

修改

我把重点放在了这个事实,即使用DataTemplates,你不再有绑定错误了。具有共同属性的对象与没有它们的对象之间没有太多差异。

无论如何,我们假设Data1Data2都来自BaseData类。这是一个简单的代码:

public class BaseData
{
    public bool IsValid { get; set; }
}

这样IsValidData1Data2的公共属性。现在您可以选择两种可能的解决方案:

  1. 您将IsValid属性添加到“隐式”DataTemplates。
  2. 您创建了一个“基础”DataTemplate(用于BaseData个对象),您可以在“隐式”DataTemplates中重复使用它(专业版:您必须编写更少的XAML - 缺点:它可能会对UI产生影响性能)
  3. 关于第二个解决方案,您的DataTemplates将变为:

    <Window.Resources>
        <CollectionViewSource x:Key="colors" Source="{Binding Path=Colors, Mode=OneTime}" />
    
        <DataTemplate x:Key="{x:Type local:BaseData}">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="80" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
    
                <TextBlock Text="Is valid" VerticalAlignment="Center" />
                <CheckBox IsChecked="{Binding IsValid}" Margin="5" Grid.Column="1" />
            </Grid>
        </DataTemplate>
    
        <DataTemplate DataType="{x:Type local:Data1}">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="80" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
    
                <TextBlock Text="Name" VerticalAlignment="Center" />
                <TextBox Text="{Binding Name}" Grid.Column="1" Margin="5" />
    
                <TextBlock Text="Description" Grid.Row="1" VerticalAlignment="Center" />
                <TextBox Text="{Binding Description}" Grid.Column="1" Grid.Row="1" Margin="5" />
    
                <ContentPresenter Grid.Row="2" Grid.ColumnSpan="2" 
                                    ContentTemplate="{StaticResource {x:Type local:BaseData}}" />
            </Grid>
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:Data2}">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="80" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
    
                <TextBlock Text="Alias" VerticalAlignment="Center" />
                <TextBox Text="{Binding Alias}" Grid.Column="1" Margin="5" />
    
                <TextBlock Text="Color" Grid.Row="1" VerticalAlignment="Center" />
                <ComboBox Text="{Binding Color}" Grid.Column="1" Grid.Row="1" Margin="5"
                            ItemsSource="{Binding Source={StaticResource colors}}" />
    
                <ContentPresenter Grid.Row="2" Grid.ColumnSpan="2" 
                                    ContentTemplate="{StaticResource {x:Type local:BaseData}}" />
            </Grid>
        </DataTemplate>
    </Window.Resources>
    

答案 2 :(得分:0)

工作(但很糟糕)的解决方案是在代码隐藏中使用绑定:

XAML:

<TextBox x:Name="textA" />
<TextBox x:Name="textB" />

CS:

public partial class MainWindow : Window
{

    ...

    void SetBindings()
    {
        BindingOperations.ClearAllBindings(textA);
        BindingOperations.ClearAllBindings(textB);
        DataContext = null;
        Bind(textA, "A");
        Bind(textB, "B");
        DataContext = this;
    }

    void Bind(UIElement element, string name)
    {
        if (Config?.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance) != null)
        {
            BindingOperations.SetBinding(element, TextBox.TextProperty, new Binding("Config." + name));
            element.Visibility = Visibility.Visible;
        }
        else
            element.Visibility = Visibility.Collapsed;
    }
}

这里的关键是在配置发生变化时调用SetBindings(),首先解除绑定(忽略DataContext操作,它们只是因为缺少正确的ViewModel而在这里,请确保在取消绑定之前不要升级Config已更改的事件!)然后在代码隐藏中绑定一些反射检查以避免绑定到不存在的属性以及控制可见性。

我必须使用这个解决方案,直到更好的方式来......如果它来了。

答案 3 :(得分:-1)

要隐藏您不想显示的控件,只需将Visibility属性(使用BooleanToVisibilityConverter)绑定到主视图模型中的属性即可。

<TextBox Text="{Binding Config.B}" Visibility="{Binding ShowConfigB, Converter={StaticResource BooleanToVisibilityConverter}, Mode=OneWay}"/>

并在ViewModel中

public bool ShowConfigB
{
    get
    {
      return (Config.GetType() == typeof(ConfigType2));
    }
}

我认为你不能仅仅通过xaml来阻止绑定错误。您可以在代码中添加或删除绑定,具体取决于使用BindingOperations.SetBinding和BindingOperations.ClearBinding使用的配置类。

请记住,用户看不到绑定错误。如果他们出于某种原因影响了表现,我只会担心他们。