【发布时间】:2014-09-03 16:57:34
【问题描述】:
我创建了一个继承自 TextBox 类的自定义控件 CustomTextBox。我创建了一个名为 CustomTextProperty 的依赖属性。
我已将此 DP 与我的 Viewmodel 属性绑定。
在注册 DP 时,我已经给出了属性更改回调,但它只会在我的控件最初在我的 xaml 加载时获取绑定数据时被调用一次。
当我尝试从视图中设置我的控件时,绑定的 VM 属性设置器不会被调用,并且 propertychangecallback 也不会被触发。
请帮忙!!
代码片段如下:
我的自定义控件
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();
}
【问题讨论】:
-
邮政编码,你是如何从后面的代码中设置它的?
-
设置
DataContext的代码在哪里?您是否在 XAML 或代码隐藏中的某处设置了DataContext?您发布的所有内容看起来都可以正常工作。 -
感谢您的回复...我已经编辑了上面的代码,显示要设置为我的 ViewModel 类实例的数据上下文。