C# WPF usercontrol双向绑定依赖项属性
我在usercontrol中创建了一个依赖项属性,但是usercontrol中的更改没有通知Viewmodel 用户控制C# WPF usercontrol双向绑定依赖项属性,c#,wpf,user-controls,dependency-properties,C#,Wpf,User Controls,Dependency Properties,我在usercontrol中创建了一个依赖项属性,但是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"
<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>
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"); }
}
}
将UserControl中的
TextBox.Text
属性绑定到其SampleProperty
,如下所示:
<TextBox Text="{Binding SampleProperty,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
public static readonly DependencyProperty
SamplePropertyProperty = DependencyProperty.Register(
"SampleProperty", typeof(string), typeof(UserControl1),
new FrameworkPropertyMetadata(
null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
另一种方法是ElementName绑定。首先将
x:Name
属性分配给UserControl(例如x:Name=“MyUC”
),然后将绑定更改为:
<TextBox Text="{Binding ElementName=MyUC, Path=SampleProperty}"/>
您还没有编写任何将TextBox.Text
属性的更改传递到SampleProperty
的代码。您还应该在那里使用一个绑定,RelativeSource={RelativeSource AncestorType=UserControl}
@Clemens我需要为UserControl使用viewmodel吗?在这种情况下不需要。但是,UserControl也可以直接绑定到视图模型的SampleText
属性。那么就根本不需要SampleProperty
。真不敢相信我读了这么多关于自定义用户控件和DependencyProperties的教程和示例,没有一个提到解决将值传递回模型的FrameworkPropertyMetadata。干得好!
<TextBox Text="{Binding SampleProperty,
RelativeSource={RelativeSource AncestorType=UserControl}}"/>
public static readonly DependencyProperty
SamplePropertyProperty = DependencyProperty.Register(
"SampleProperty", typeof(string), typeof(UserControl1),
new FrameworkPropertyMetadata(
null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
<TextBox Text="{Binding ElementName=MyUC, Path=SampleProperty}"/>