首页 文章

Usercontrol数据绑定属性更改了MVVM

提问于
浏览
0

我正在使用WPF并使用数据绑定 .

我想创建一个UserControl,它具有可用于数据绑定的属性 .

此外,如果属性更改,我想更新UserControl中的一些其他属性 .

例如,

public class MyControl : UserControl
{
....
....
....
....

        public ViewStyles CurrentView
        {
            get { return (ViewStyles)GetValue(CurrentViewProperty); }
            set
            {
                SetValue(CurrentViewProperty, value);
                UpdateView();
            }
        }
        public static readonly DependencyProperty CurrentViewProperty = DependencyProperty.Register("CurrentView", typeof(ViewStyles), typeof(ComboView));

....
.....
.....
.....
}

问题来了:

使用ViewModel,其中有一个属性ViewStyle,它绑定到上面的CurrentView .

另一个控件组合框也与ViewModel中的ViewStyle数据绑定 .

实际上,我想使用组合框来选择我控制的不同视图 . 如何在MVVM中实现它?

我试过上面的方法 . 但是,UI(MyControl的不同ViewStyles)没有改变 . 它只会在我用鼠标点击它时改变 .

谢谢 .

XAML :( MyControl)

<Views:MyControl Grid.Column="1" Grid.Row="1" Height="505" HorizontalAlignment="Left" Margin="2,0,0,0" Name="comboView1" VerticalAlignment="Top" Width="983" 
                 ViewStyle="{Binding Path=CurrentView}" BorderThickness="5" BorderBrush="Black" ItemsSource="{Binding Path=Images}" 
                 SelectedIndex="{Binding Path=CurrentIndex}" Foreground="White" 

</Views:MyControl>

XAML :( ComboBox)

<ComboBox Margin="0,3,1,0" Width="178" HorizontalAlignment="Right" Name="ViewDDBox" FontSize="13" Foreground="#FFF6F3F3" Background="#FF444444"
          BorderThickness="2" Height="23" VerticalAlignment="Top" Grid.Column="1" 
          ItemsSource="{Binding Path=ViewTypes}" IsEnabled="True" SelectedValue="{Binding Path=CurrentView, Mode=TwoWay}">
         </ComboBox>

假设在Combobox中选择后,将更改MyControl的视图(某些UI效果) . 但是现在,只有当我使用鼠标点击MyControl时它才会改变 .

2 回答

  • 0

    CurrentView属性setter中的 UpdateView() 会引发巨大的红旗!您应该 never 在依赖项属性设置器中具有除 SetValue 之外的任何内容,因为xaml的某些方面直接调用 SetValue 而不是通过该属性 . 始终使用强制属性回调(如果要在设置之前验证数据)或属性更改回调(如果要在更改属性后执行操作,如下面的示例所示) .

    你应该这样做:

    public static DependencyProperty CurrentViewProperty = 
        DependencyProperty.Register("CurrentView", typeof(ViewStyles), typeof(ComboView),
        new FrameworkPropertyMetadata(CurrentViewPropertyChanged));
    
    private static void CurrentViewPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MyControl mc = (MyControl)d;
        mc.UpdateView();
    }
    
  • 1

    为什么不创建模板化控件,然后将控件的视图绑定到viewmodel上的属性,而不是绑定视图?

    您可能还必须在模板上使用数据模板触发器来获得所需的功能 .

    查看this article以获取有关模板基础知识的帮助,并查看this one以获得更深入的讨论 .

相关问题