2015-07-21 36 views
1

我已经创建了一个自定义的用户控件,它由一个AutoCompleteBox和一个Selected Item组成......直到现在我已经用一种我不喜欢的方式实现它了......我的意思是,有一个XAML视图,一个Viewmodel,并且在视图模型中我加载了存储过程中的数据。 由于“自动完成”框是第三方UserControl,因此我已将其添加到XAML视图,并未将其定义为自定义用户控件。这样做的最佳做法是什么? 我认为的事实,我使用Catel MVVM作为框架是irrilevant现在..用MVVM和Catel自定义用户控件

感谢

更新#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

我保持这种toghether,因为这是一个相关的问题... 在某些视图模型我用DeferValidationUntilFirstSaveCall = TRUE;在构造函数中禁用加载时的验证,但我的自定义usercontrols显示红色边框周围......我该怎么做才能将该信息传播给嵌套的usercontrols?

enter image description here

再次感谢

回答

1

为吨的例子见Orc.Controls。它是一个开源库,拥有许多用Catel构建的用户控件,甚至包含一个自动完成框。

+0

我看着他们,他们是非常类似地雷..我只是一个问题,这就是为什么我打开这个线程...看到我的更新,请 – advapi

+0

你检查的ViewToViewModel的东西(这也是在演示中)? –

+0

我在上面我错过了[ViewToViewModel(MappingType = ViewToViewModelMappingType.TwoWayViewWins)]属性! – advapi