【问题标题】:User Control Data Binding in Silverlight/MVVMSilverlight/MVVM 中的用户控件数据绑定
【发布时间】:2023-03-24 07:10:01
【问题描述】:

DependencyPropertys 默认为双向绑定吗?如果不是怎么指定?

我问的原因是我有以下导致我出现问题的用户控件...

<UserControl x:Class="SilverlightApplication.UserControls.FormItem_TextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
>

<StackPanel Style="{StaticResource FormItem_StackPanelStyle}" >

    <TextBlock x:Name="lbCaption" Style="{StaticResource FormItem_TextBlockStyle}" />
    <TextBox x:Name="tbItem" Style="{StaticResource FormItem_TextBoxStyle}" />

</StackPanel>

后面的代码是……

public partial class FormItem_TextBox : UserControl
{

    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(FormItem_TextBox), new PropertyMetadata(string.Empty, ValueChanged));     
    public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register("Caption", typeof(string), typeof(FormItem_TextBox), new PropertyMetadata(string.Empty, CaptionChanged));

    public string Value
    {
        get { return (String)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }

    public string Caption
    {
        get { return (String)GetValue(CaptionProperty); }
        set { SetValue(CaptionProperty, value); }
    }

    private static void ValueChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {
        (source as FormItem_TextBox).tbItem.Text = e.NewValue.ToString();
    }

    private static void CaptionChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
    {           
        (source as FormItem_TextBox).lbCaption.Text = e.NewValue.ToString();
    }

    public FormItem_TextBox()
    {
        InitializeComponent();
    }

}

在我的页面中,我使用这样的控件....

<UC:FormItem_TextBox Caption="First Name: " Value="{Binding Path=FirstName, Mode=TwoWay}" />

但文本框的任何更新都不会发送到模型。

如果我像这样使用标准文本框......

<TextBlock Text="Firstname:"/>
<TextBox Text="{Binding Path=FirstName, Mode=TwoWay}" />

那么这两种数据绑定的工作方式就完美了。任何想法我的控制有什么问题?

干杯,

ETFairfax。

【问题讨论】:

    标签: silverlight user-controls mvvm


    【解决方案1】:

    在您的用户控件中,您无法知道文本框中的值何时更新。您需要为 tbItem 文本框上的 TextChanged 事件添加事件处理程序,然后将 Value 属性的值设置为新值。

    【讨论】:

    • 感谢科比的回复。我以为会是这样,但觉得有点奇怪,因为 ValueChanged 有(来源为 FormItem_TextBox).tbItem.Text = e.NewValue.ToString(); ……那种感觉就像我要绕来绕去;你明白我的意思吗?无论如何,你的建议是有效的,所以这才是最重要的!!!谢谢。
    • ValueChanged 是从 VM 到控件。 TextChanged 处理程序用于返回另一个方向。
    猜你喜欢
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2010-11-18
    • 2011-02-03
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    相关资源
    最近更新 更多