2014-09-03 91 views
0

我已經創建了一個從TextBox類繼承的自定義控件CustomTextBox。我創建了一個名爲CustomTextProperty的依賴項屬性。WPF自定義控件依賴屬性setter沒有被調用?

我用我的Viewmodel屬性綁定了這個DP。

在註冊DP時,我給出了屬性更改回調,但只有當我的控件在我的xaml加載時獲取綁定數據時纔會調用一次。

當我嘗試從視圖中設置我的控件時,綁定的VM屬性設置程序不會被調用,也不會觸發propertychangecallback。

請幫忙!!

代碼如下snipet:

我的自定義控制

class CustomTextBox : TextBox 
{ 
    public static readonly DependencyProperty CustomTextProperty = DependencyProperty.Register("CustomText", 
                   typeof(string), typeof(CustomTextBox), 
                   new FrameworkPropertyMetadata("CustomTextBox", 
                   FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, 
                   new PropertyChangedCallback(OnCustomPropertyChange))); 

public string CustomText 
{ 
    get { return (string)GetValue(CustomTextProperty); } 
    set { SetValue(CustomTextProperty, value); } 
} 

private static void OnCustomPropertyChange(DependencyObject d, DependencyPropertyChangedEventArgs e) 
{ 
    // This is Demo Application. 
    // Code to be done Later... 
} 
} 

我的視圖模型:

public class ViewModel : INotifyPropertyChanged 
{ 
private string textForTextBox; 

public string TextForCustomTextBox 
{ 
    get 
    { 
    return this.textForTextBox; 
    } 
    set 
    { 
    this.textForTextBox = value; 

    this.OnPropertyChange("TextForCustomTextBox"); 
    } 
} 

public event PropertyChangedEventHandler PropertyChanged; 

public void OnPropertyChange(string name) 
{ 
    PropertyChangedEventHandler handler = PropertyChanged; 

    if (handler != null) 
    { 
    handler(this, new PropertyChangedEventArgs(name)); 
    } 
} 
} 

我的XAML代碼用結合:

<custom:CustomTextBox x:Name="CustomTextBox" 
            CustomText="{Binding TextForCustomTextBox, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
            Grid.Row="1" HorizontalAlignment="Center" Width="200" Height="50" /> 

我的代碼背後設置DataContext:

// My View Constructor 
public View1() 
{ 
    InitializeComponent(); 

    this.DataContext = new ViewModel(); 
} 
+0

郵政編碼,你如何從後面的代碼設置它? – 2014-09-03 17:10:06

+0

設置'DataContext'的代碼在哪裏?你在XAML或代碼隱藏的某個地方設置了一個'DataContext'嗎?你發佈的所有內容看起來都會起作用。 – 2014-09-03 17:14:37

+0

感謝您的回覆......我編輯了上面顯示datacontext的代碼,將其設置爲我的ViewModel類實例。 – Deepanshu 2014-09-03 17:23:51

回答

1

你說,你聲明的CustomText DependencyProperty和數據它綁定到您的視圖模型TextForCustomTextBox財產,這一點是正確的。但是,當你說你試圖從視圖中設置你的財產時,你錯了。

實際上所做的是設置從視圖中CustomTextBox .Text財產,沒有連接到您的CustomTextBox.CustomText性質是什麼。您可以將他們這個樣子,雖然我不太清楚這點會是什麼:

<Views:CustomTextBox x:Name="CustomTextBox" Text="{Binding CustomText, RelativeSource={ 
    RelativeSource Self}, UpdateSourceTrigger=PropertyChanged}" CustomText="{Binding 
    TextForCustomTextBox, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
    Grid.Row="1" HorizontalAlignment="Center" Width="200" Height="50" /> 
+0

謝謝Sheridan ...您提供的解決方案使其工作。其實沒有這樣做的意義,但我正在學習WPF,並希望學習這項技術的每一個進出口。你能爲我推薦任何用於學習WPF的好文檔或手冊嗎? – Deepanshu 2014-09-04 08:53:04

0

嘗試設置你的DataContext實際初始化之前,因此可用於創建窗體/控件對象時。如果它以前找不到,那是什麼可能導致失敗的綁定。

相關問題