制作OneWayToSource /双向自定义控制绑定 [英] Making a OneWayToSource/TwoWay binding on custom control

查看:263
本文介绍了制作OneWayToSource /双向自定义控制绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个依赖属性的自定义控制,定义如下:

I have a custom control with a dependency property, defines as follows:

public class TemplatedTextBox : TextBox
{
    public static readonly DependencyProperty SearchStringProperty =
        DependencyProperty.Register("SearchString", typeof(string), typeof(TemplatedTextBox), new UIPropertyMetadata(string.Empty));

    public string SearchString
    {
        get { return (string)GetValue(SearchStringProperty); }
        set { SetValue(SearchStringProperty, value); }
    }
}



我用下面的控件模板:

I use the following control template:

    <WpfApp:TemplatedTextBox>
        <WpfApp:TemplatedTextBox.Template>
            <ControlTemplate TargetType="{x:Type WpfApp:TemplatedTextBox}">
                <StackPanel Height="20" Orientation="Horizontal">
                    <TextBlock Text="Search String :"/>
                    <TextBox x:Name="SearchTextBox"  Width="200" Text="NEED TO BE BINDED TO SearchString!"/>
                </StackPanel>
            </ControlTemplate>
        </WpfApp:TemplatedTextBox.Template>
    </WpfApp:TemplatedTextBox>



我要绑定 SearchTextBox 文本属性,以我的 SearchString在属性在 OneWayToSource 双向结合模式。

I want to bind SearchTextBox's Text property to my SearchString property in a OneWayToSource or TwoWay binding mode.

我试过:

Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SearchString, Mode=OneWayToSource}"

这并不什么都不做

Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SearchString, Mode=TwoWay}"

Text="{TemplateBinding SearchString}"

这在一个方向上工作得很好,当我编程的方法修改 SearchString在文本文本框的变化,而不是其他方式

Which works fine in one direction when I programatically change SearchString the Text on TextBox changes, but not the other way

我也试图使 SearchString在常规属性,并使用绑定的RelativeSource 在各种模式取值,但没有奏效。

I've also tried making SearchString a regular property and bind it using RelativeSource in all sorts of Modes but it didn't work.

这是定期查看到视图模型做绑定,所以我是什么在这里失踪?

This is a pretty straight forward thing to do in regular View-to-ViewModel binding, so what am I missing here?

推荐答案

我只是尝试它和它按预期工作。
难道是简单的东西,例如,你不会离开文本框输入字符,以便绑定不触发后?

I just tried it and it works as expected. Could it be something simply, e.g. you are not leaving the textbox after entering the characters so the binding does not trigger ?

尝试添加 UpdateSourceTrigger = PropertyChanged的,触发每个字符的结合输入。

Try to add UpdateSourceTrigger=PropertyChanged, to trigger the binding on each character entered.

这篇关于制作OneWayToSource /双向自定义控制绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆