WPF 用户控件双向绑定依赖属性

WPF usercontrol Twoway binding Dependency Property(WPF 用户控件双向绑定依赖属性)
本文介绍了WPF 用户控件双向绑定依赖属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I created a Dependency Property in the usercontrol, but however changes in the usercontrol was NOT notified to the Viewmodel

Usercontrol

<UserControl x:Class="DPsample.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <TextBox x:Name="txtName"></TextBox>
</Grid>

UserControl.cs

/// <summary>
/// Interaction logic for UserControl1.xaml
/// </summary>
public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    #region SampleProperty 

    public static readonly DependencyProperty SamplePropertyProperty
                                            = DependencyProperty.Register("SampleProperty", 
                                            typeof(string), 
                                            typeof(UserControl1), 
                                            new PropertyMetadata(OnSamplePropertyChanged));


    public string SampleProperty
    {
        get { return (string)GetValue(SamplePropertyProperty); }
        set { SetValue(SamplePropertyProperty, value); }
    }


    static void OnSamplePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        (obj as UserControl1).OnSamplePropertyChanged(e);
    }
    private void OnSamplePropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        string SamplePropertyNewValue = (string)e.NewValue;

        txtName.Text = SamplePropertyNewValue;
    }

    #endregion
}

MainWindow

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:DPsample" x:Class="DPsample.MainWindow"
    Title="MainWindow" Height="350" Width="525">
<Grid>

    <local:UserControl1 SampleProperty="{Binding SampleText,Mode=TwoWay}" HorizontalAlignment="Left" Margin="76,89,0,0" VerticalAlignment="Top" Width="99"/>
    <Button Content="Show" HorizontalAlignment="Left" Margin="76,125,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

</Grid>

MainWindow.cs

 public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainViewModel();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var item = this.DataContext as MainViewModel;
        MessageBox.Show(item.SampleText.ToString());
    }

MainViewModel.cs

public class MainViewModel : NotifyViewModelBase
{
    public MainViewModel()
    {
        this.SampleText = "test";           
    }

    private string _sampleText;
    public string SampleText
    {
        get { return _sampleText; }
        set { _sampleText = value; OnPropertyChanged("SampleText"); }
    }
}

解决方案

Bind the TextBox.Text property in the UserControl to its SampleProperty like this:

<TextBox Text="{Binding SampleProperty,
                RelativeSource={RelativeSource AncestorType=UserControl}}"/>

Now you could simply remove your OnSamplePropertyChanged callback.


You might also register SampleProperty to bind two-way by default like this:

public static readonly DependencyProperty
    SamplePropertyProperty = DependencyProperty.Register(
        "SampleProperty", typeof(string), typeof(UserControl1),
        new FrameworkPropertyMetadata(
            null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

这篇关于WPF 用户控件双向绑定依赖属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)