2014-09-03 90 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实际初始化之前,因此可用于创建窗体/控件对象时。如果它以前找不到,那是什么可能导致失败的绑定。

相关问题