我有一个带有依赖项属性的UserControl
,我需要将此属性绑定到父ViewModel中的CLR属性。我已经编写了一个小应用程序来证明这个问题。
用户控件
<UserControl
...
x:Name="usr">
<Grid>
<TextBox Text="{Binding SomeProperty, ElementName=usr}"/>
</Grid>
</UserControl>
背后的代码:
public partial class UserControl1 : UserControl
{
public string SomeProperty
{
get { return (string)GetValue(SomePropertyProperty); }
set { SetValue(SomePropertyProperty, value); }
}
public static readonly DependencyProperty SomePropertyProperty =
DependencyProperty.Register("SomeProperty", typeof(string), typeof(UserControl1), new PropertyMetadata(null));
public UserControl1()
{
InitializeComponent();
}
}
家长视图
<Window ... >
<Window.DataContext>
<ViewModels:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<Controls:UserControl1 SomeProperty="{Binding SomeText, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</Window>
父ViewModel
public class MainWindowViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
private string _SomeText;
public string SomeText
{
get { return _SomeText; }
set
{
_SomeText = value;
OnPropertyChanged();
}
}
}
基本上,我需要的是在UserControl中输入的任何内容TextBox
(SomeProperty
属性)需要更新ViewModel的SomeText
属性
我不需要双向绑定。
为代码海洋道歉,但如果有人想要它,它就在那里。