Making a OneWayToSource/TwoWay binding on custom control

你。 提交于 2019-12-08 04:27:21

问题


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>

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

I've tried:

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

Which doesn't do nothing.

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

And

Text="{TemplateBinding SearchString}"

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

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?


回答1:


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 ?

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



来源:https://stackoverflow.com/questions/19487896/making-a-onewaytosource-twoway-binding-on-custom-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!