WPF usercontrol Twoway绑定依赖属性

时间:2014-09-23 07:09:55

标签: c# wpf user-controls dependency-properties

我在usercontrol中创建了一个Dependency属性,但是usercontrol中的更改未通知Viewmodel

用户控件

<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
}

主窗口

<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"); }
    }
}

2 个答案:

答案 0 :(得分:40)

将UserControl中的TextBox.Text属性绑定到SampleProperty,如下所示:

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

现在您只需删除OnSamplePropertyChanged回调。


您也可以注册SampleProperty默认绑定双向,如下所示:

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

答案 1 :(得分:2)

另一种方法是ElementName Binding。首先将x:Name属性分配给UserControl(例如x:Name="MyUC"),然后将绑定更改为:

<TextBox Text="{Binding ElementName=MyUC, Path=SampleProperty}"/>