【问题标题】:How can I update the source from a custom control with dependency properties in silverlight?如何从 Silverlight 中具有依赖属性的自定义控件更新源?
【发布时间】:2013-10-25 20:35:56
【问题描述】:

我创建了一个扩展 RichTextBox 的自定义控件,以便我可以为 xaml 属性创建绑定。只要我只是从视图模型中更新属性,这一切都很好,但是当我尝试在 Richtextbox 中编辑时,属性不会更新回来。

我在扩展版的richtextbox中有如下代码。

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register ("Text", typeof(string), typeof(BindableRichTextBox), new PropertyMetadata(OnTextPropertyChanged));

    private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var rtb = d as BindableRichTextBox;
        if (rtb == null) 
            return;

        string xaml = null;
        if (e.NewValue != null)
        {
            xaml = e.NewValue as string;
            if (xaml == null)
                return;
        }

        rtb.Xaml = xaml ?? string.Empty;
    }

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

在视图中我已经设置了这样的绑定

<Controls:BindableRichTextBox Text="{Binding XamlText, Mode=TwoWay}"/>

在视图模型中,我将 XamlText 创建为普通属性,并在更新时调用 NotifyPropertyChanged 事件。

我希望当用户在 lostfocus 上或直接在编辑期间在 RichTextBox 中输入文本时更新绑定的 XamlText,这并不重要。

如何更改代码以实现这一点?

【问题讨论】:

    标签: c# silverlight dependency-properties two-way


    【解决方案1】:

    您需要监听BindableRichTextBoxXaml-property 的更改,并相应地设置Text-property。这里有an answer,描述了如何实现这一点。使用其中描述的方法将导致以下代码(未经测试):

    public BindableRichTextBox()
    {
        this.RegisterForNotification("Xaml", this, (d,e) => ((BindableRichTextBox)d).Text = e.NewValue);
    }
    
    public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
    {
        var binding = new Binding(propertyName) { Source = element };
        var property = DependencyProperty.RegisterAttached(
            "ListenAttached" + propertyName,
            typeof(object),
            typeof(UserControl),
            new PropertyMetadata(callback));
        element.SetBinding(property, binding);
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-24
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 2016-01-07
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      相关资源
      最近更新 更多