我已经创建了一个从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