2013-07-22 45 views
0

我在這裏問了一個類似的問題WPF MVVM User Control。我得到了一些答案,但他們都離開了,所以我想我不清楚我想做什麼......WPF MVVM將用戶控件綁定到主窗口視圖模型

我正在使用MVVM的WPF應用程序。該應用程序使用基於組件的方法構建,因此我定義了一些用戶控件,這些控件將在整個應用程序中使用。作爲一個例子,我有一個地址控件。我想在整個應用程序中使用它多個地方。這是一個例子。在這裏看到:

http://sdrv.ms/1aD775H

與綠色邊框的部分是地址控制。該控件擁有自己的視圖模型。

當我把它放在一個窗口或其他控件上時,我需要告訴它爲客戶加載地址的PK。所以,我創建了一個用戶ID的DependencyProperty:

public partial class AddressView : UserControl 
{ 
    public AddressView() 
    { 
     InitializeComponent(); 
    } 

    public static DependencyProperty CustomerIdProperty = DependencyProperty.Register("CustomerId", typeof(int), typeof(AddressView), 
     new UIPropertyMetadata(0, AddressView.CustomerIdPropertyChangedCallback, AddressView.CustomerIdCoerce, true)); 


    public int CustomerId 
    { 
     // THESE NEVER FIRE 
     get { return (int)GetValue(CustomerIdProperty); } 
     set { SetValue(CustomerIdProperty, value); } 
    } 

    private static void CustomerIdPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs args) 
    { 
     // THIS NEVER FIRES 
     AddressView instance = (AddressView)d; 
     instance.CustomerId = (int)args.NewValue; 
    } 
    enter code here 
    private static object CustomerIdCoerce(DependencyObject d, object value) 
    { 
     return value; // <=== THIS FIRES ON STARTUP 
    } 
} 

然後在MainWindowView我:

<vw:AddressView Grid.Row="1" 
       Grid.Column="0" 
       x:Name="AddressList" 
       CustomerId="{Binding ElementName=TheMainWindow, Path=SelectedCustomer.Id, Mode=TwoWay}"/> 

注意我在用戶控件的CS意見。 Coerce在啓動時着火。回調不會觸發,也不會觸發CustomerId getter或setter。

我想發生這樣似乎很簡單,我只是不能讓它工作....

當客戶選擇在客戶應傳遞到地址用戶控件。然後在地址UserControl的VM中應該處理獲取數據的&。

所以,再一次,2個問題:

1)任何人都看到了什麼問題?

2)UserControl DP如何將PK發送到ViewModel?

如果任何人的興趣,我的樣本項目是在這裏:http://sdrv.ms/136bj91

感謝

+0

嘗試添加UpdateSourceTrigger = PropertyChanged到您的綁定,當選擇更改您的控件將不會得到更新,否則。 – sldev

+0

你可以發佈你的usercontrol xaml頁面的代碼.. – loop

+0

可能的重複的[WPF MVVM用戶控件](http://stackoverflow.com/questions/17159580/wpf-mvvm-user-control) – Will

回答

0

試試這個:

CustomerId="{Binding RelativeSource={RelativeSource FindAncestor, 
AncestorType={x:Type Window}}, Path=DataContext.YourSelectedItem.TheProperty}" 

我不知道如何在窗口管理您的入圍項目,所以請改變yourSelectedItem.TheProperty據此。

Thaks

+0

好的,這工作 - 但只有一次。回調方法僅在第一次選擇客戶時觸發。 – CoderForHire

+0

你可以在代碼 –

+0

中粘貼你的SelectedItem的實現當然,我創建了一個小沙箱項目來學習這個。它在這裏http://sdrv.ms/13fM5EY。 – CoderForHire

0

CustomerId getter和setter將永遠不會觸發這種情況。他們在那裏只是作爲幫助者的方法,如果你想從你的代碼後面訪問CustomerIdProperty屬性。您的CustomerIdPropertyChangedCallback方法不會觸發,因爲您的綁定表達式不正確。您需要將窗口本身結合的MainWindowDataContext,而不是:

... 
CustomerId="{Binding ElementName=TheMainWindow, Path=DataContext.SelectedCustomer.Id}" 
... 

此外,確保當綁定到ComboBox的屬性更改,您所呼叫的INotifyPropertyChangedPropertyChanged事件。

相關問題