【问题标题】:Silverlight Custom User Controls and Dependancy property IssueSilverlight 自定义用户控件和依赖属性问题
【发布时间】:2010-10-07 03:35:57
【问题描述】:

我有一个名为 Field 的自定义用户控件:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock Grid.Row="0" Grid.Column="0" Name="LblName"/>
    <TextBox Grid.Row="0" Grid.Column="1" HorizontalContentAlignment="Left" Name="TxtValue"/>
</Grid>

在 CS 文件中,我公开了以下属性,它只是设置文本框的“.text”值。

    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
        "Value",
        typeof(string),
        typeof(Field),
        new PropertyMetadata(
            default(string),
            (source, args) => (source as Field).TxtValue.Text = (string)args.NewValue
        )
    );

    [Category("Custom")]
    public string Value
    {
        get
        {
            return (string)this.GetValue(ValueProperty);
        }
        set
        {
            this.SetValue(ValueProperty, value);
        }
    }

第一个问题。这是我们传播子用户控件依赖属性的正确方法,通过父用户控件进行备份,以便可以从页面 xaml 进行设置?我在网上浏览了一下,考虑到这是编写自定义控件时相当原始的事情,所以没有太多内容。

提供有关大图的详细信息,我有客户详细信息页面,一些控件绑定到包含在可观察集合中的客户对象。如果我将页面上的文本框(包含在字段控件中)的值从“xxxx”更改为“yyyy”,我总是会返回“xxxx”。似乎 getter 周围的某个地方出了点问题?

【问题讨论】:

    标签: silverlight user-controls


    【解决方案1】:

    这绝对是朝着允许属性传播的正确方向迈出的一步。

    如果这是一个真正的自定义控件(从 Control 派生),您可能希望使用 {TemplateBinding Value},并且在 OnApplyTemplate 方法中设置模板部分之后,您可能还应该连接到 TextBox 上的 TextChanged 事件.这样,您也可以让它更新您的底层 TxtValue 依赖属性。

    如果这是一个 UserControl,您也许可以使用 Binding,但您可以使用的选项更少。正如您所拥有的,您的属性更改回调函数仅朝一个方向前进:您只设置 Text 值,您永远不会对其做出反应。

    让我们希望那里的文档有所改进。

    【讨论】:

      猜你喜欢
      • 2010-12-16
      • 2011-03-24
      • 2016-01-07
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 1970-01-01
      • 2012-08-29
      • 1970-01-01
      相关资源
      最近更新 更多