【问题标题】:Making a OneWayToSource/TwoWay binding on custom control在自定义控件上进行 OneWayToSource/TwoWay 绑定
【发布时间】:2013-10-21 06:50:31
【问题描述】:

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

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); }
    }
}

我使用以下控件模板:

    <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>

我想以OneWayToSourceTwoWay 绑定模式将SearchTextBoxText 属性绑定到我的SearchString 属性。

我试过了:

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

什么都不做。

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

Text="{TemplateBinding SearchString}"

当我以编程方式更改SearchString Text 上的TextBox 更改时,这在一个方向上效果很好,但在另一个方向上效果不佳

我也尝试过将SearchString 设为常规属性,并在各种Modes 中使用RelativeSource 绑定它,但它不起作用。

这是在常规 View-to-ViewModel 绑定中非常简单的事情,那么我在这里缺少什么?

【问题讨论】:

    标签: c# wpf data-binding custom-controls


    【解决方案1】:

    我刚刚尝试过,它按预期工作。 可能是简单的东西,例如输入字符后您没有离开文本框,因此不会触发绑定?

    尝试添加UpdateSourceTrigger=PropertyChanged,以触发对输入的每个字符的绑定。

    【讨论】:

    • 我不敢相信我总是在像UpdateSourceTrigger=PropertyChanged 这样的愚蠢的东西上失败......谢谢你!
    • @Omribitan 每个人都这样做。文本框默认没有属性更改总是让我烦恼,这对验证很有意义。
    猜你喜欢
    • 2011-08-06
    • 2010-10-10
    • 2012-02-05
    • 1970-01-01
    • 2011-12-30
    • 2019-02-08
    • 1970-01-01
    • 2012-01-28
    相关资源
    最近更新 更多