我已經創建了一個從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();
}
郵政編碼,你如何從後面的代碼設置它? – 2014-09-03 17:10:06
設置'DataContext'的代碼在哪裏?你在XAML或代碼隱藏的某個地方設置了一個'DataContext'嗎?你發佈的所有內容看起來都會起作用。 – 2014-09-03 17:14:37
感謝您的回覆......我編輯了上面顯示datacontext的代碼,將其設置爲我的ViewModel類實例。 – Deepanshu 2014-09-03 17:23:51