【问题标题】:Custom Usercontrol with MVVM and Catel使用 MVVM 和 Catel 自定义用户控件
【发布时间】:2015-07-21 12:51:57
【问题描述】:

我创建了一个自定义用户控件,它由一个带有所选项目的 AutoCompleteBox 组成......直到现在我已经以一种我不喜欢的方式实现它......我的意思是我有一个 XAML 视图,一个Viewmodel 并在 viewmodel 中我从存储过程加载数据。 由于自动完成框是第三方用户控件,我已将其添加到 XAML 视图中,并且未定义为自定义用户控件。这样做的最佳做法是什么? 我认为我现在将 Catel 用作 MVVM 框架这一事实令人不快..

谢谢

更新 #1

我的用户控件需要有一些通过 XAML 传递的属性,例如 (LoadDefaultValue)

<views:PortfolioChooserView x:Name="PortfolioChooserView" DataContext="{Binding Model.PortfolioModel}" Height="25" LoadDefaultValue="True" Width="150" />

为了实现这样的场景,我必须在我的 PortfolioChooserView 中定义一个依赖属性,定义为

public bool LoadDefaultValue
    {
        get { return (bool)GetValue(LoadDefaultValueProperty); }
        set { SetValue(LoadDefaultValueProperty, value); }
    }

    public static readonly DependencyProperty LoadDefaultValueProperty = DependencyProperty.Register(
  "LoadDefaultValue", typeof(bool), typeof(PortfolioChooserView), new PropertyMetadata(default(bool)));

如果我只在 Viewmodel 中定义它,我将无法设置它。

奇怪的是,为了将它传递给视图模型,我不得不这样做

public PortfolioChooserView()
    {
        InitializeComponent();
        if (!isFirstLoad) return;

        Focusable = true;
        PortfolioCompleteBox.AllowDrop = true;
        PortfolioCompleteBox.Focus();

        DragDropManager.AddPreviewDragOverHandler(PortfolioCompleteBox, OnElementDragOver);
        DragDropManager.AddDropHandler(PortfolioCompleteBox, OnElementDrop);

        DataContextChanged += PortfolioChooserView_DataContextChanged;
        isFirstLoad = false;
    }

    void PortfolioChooserView_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var dataContext = DataContext as PortfolioModel;

        if (dataContext != null)
        {
            dataContext.LoadDefaultValue = LoadDefaultValue;
            dataContext.AllowNull = AllowNull;

            //var converter = new PortfolioConverter();

            //var portfolio = (Portfolio) converter.Convert(SelectedItem, null, null, CultureInfo.CurrentCulture);
            //dataContext.SelectedItem = portfolio;
        }
    }

但我真的不喜欢使用 DataContextChanged 事件......你看到更好的方法了吗? 谢谢

更新#2

我把这个放在一起,因为这是一个相关的问题...... 在某些视图模型上,我使用了 DeferValidationUntilFirstSaveCall = true;在构造函数中禁用加载验证,但我的自定义用户控件显示红色边框...我应该怎么做才能将该信息传播到嵌套的用户控件?

再次感谢

【问题讨论】:

    标签: wpf user-controls catel


    【解决方案1】:

    有关大量示例,请参阅 Orc.Controls。它是一个开源库,包含许多使用 Catel 构建的用户控件,甚至还有一个带有自动完成框的控件。

    【讨论】:

    • 我看过它们,它们和我的很相似。我只有一个问题,这就是我打开那个帖子的原因...请查看我的更新
    • 你检查过 ViewToViewModel 的东西(也在演示中)吗?
    • 我在上面我错过了 [ViewToViewModel(MappingType = ViewToViewModelMappingType.TwoWayViewWins)] 属性!
    猜你喜欢
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2011-03-21
    • 2010-10-31
    • 2015-02-15
    • 2013-09-21
    相关资源
    最近更新 更多