在自定义控件中使依赖项属性绑定两种方式

kat*_*tit 5 silverlight xaml

我有以下自定义控件:

<TextBox Grid.Column="3" Text="{TemplateBinding SampleValue}" />

public static readonly DependencyProperty SampleValueProperty =
            DependencyProperty.RegisterAttached("SampleValue", typeof(string), typeof(IdattFilterBox), new PropertyMetadata(null));

public string SampleValue
        {
            get { return GetValue(SampleValueProperty) as string; }
            set { this.SetValue(SampleValueProperty, value); }
        }
Run Code Online (Sandbox Code Playgroud)

在UserControl中我声明我的自定义控件我有这样的XAML:

<my:SampleBox SampleValue="{Binding SampleValue, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)

和ViewModel一样:

public string SampleValue
        {
            get
            {
                return this.sampleValue;
            }

            set
            {
                this.sampleValue = value;
            }
        }
Run Code Online (Sandbox Code Playgroud)

我不关心VM上的INotifyPropertyChanged(所以不要告诉我它:)现在它正在文本框中显示文本,就像我在VM中设置它一样.但是当我修改这个文本时 - 它不会被冒泡回VM.

我该怎么办?我想我必须在自定义控件中编写一些代码?我应该处理TextBox PART并捕获LostFocus吗?或者它如何与TemplateBinding一起使用?

Jus*_* XL 7

TemplateBinding只是OneWay.

如果您使用的是Silverlight 4,可以试试这个,

{Binding SampleValue, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}
Run Code Online (Sandbox Code Playgroud)


Mik*_*ost 4

TemplateBinding 本质上是一种方式。您需要使用 BindingMode=TwoWay

Source={Binding RelativeSource={RelativeSource TemplatedParent}}