【问题标题】:UserControl Dependency property does not workUserControl 依赖属性不起作用
【发布时间】:2015-11-06 08:36:03
【问题描述】:

我有我的用户控件。我想设置依赖属性,但我不能。

TextBoxExtended.cs

public partial class TextBoxExtended : UserControl
    {
        public static readonly DependencyProperty MyTextPropertyProperty =
        DependencyProperty.Register("MyTextProperty", typeof(string), typeof(TextBoxExtended), new UIPropertyMetadata(String.Empty));

        public string MyTextProperty
        {
            get { return (string)GetValue(MyTextPropertyProperty); }
            set { SetValue(MyTextPropertyProperty, value); }
        }

TextBoxExtended.xaml

<TextBox x:Name="tbMain" Text="{Binding MyTextProperty}"

MainWindow.xaml

<local:TextBoxExtended x:Name="TextBoxSearch" Height="30" Margin="83,38,193,285" MyTextProperty="MyTextProperty"/>

我需要事件 textchange,我使用这个代码

<local:TextBoxExtended x:Name="TextBoxSearch" Height="30" Margin="83,38,193,285" MyTextProperty="{Binding MyText, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>

但我需要在引入每个角色后进行更改

【问题讨论】:

  • 现在您没有文本框控件的来源,这就是为什么这不起作用。

标签: c# wpf user-controls


【解决方案1】:

您必须在 TextBoxExtended.xaml 中设置 Binding 的源对象,例如

<TextBox x:Name="tbMain"
    Text="{Binding MyTextProperty,
                   RelativeSource={RelativeSource AncestorType=UserControl}}" />

【讨论】:

    【解决方案2】:

    在TextBox的绑定中使用ElementName。

            <StackPanel>
                <TextBox Text="{Binding MyText, ElementName=TextBoxSearch}" ></TextBox>
                <local:TextBoxExtended x:Name="TextBoxSearch" Height="30"
                                       MyText="Hello World!!!" />
            </StackPanel>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 2017-12-24
      • 1970-01-01
      • 2014-03-31
      相关资源
      最近更新 更多