如何解决没有视图模型的WPF用户控件
我试图在WPF中创建一个简单的用户控件,没有视图模型。 我里面有一个标签和一个文本框。
ControlTextBox.xaml:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Name="LabelColumn"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Name="LabelControl"></Label>
<TextBox Grid.Column="1"
Name="TextBox"
Width="Auto"
HorizontalAlignment="Stretch"
Height="22"></TextBox>
</Grid>
ControlTextBox.xaml.cs:
public partial class ControlTextBox : UserControl
{
public ControlTextBox ()
{
InitializeComponent();
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text",typeof(string),typeof(ControlTextBox),new PropertyMetadata(default(string),new PropertyChangedCallback(OnTextChanged)));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty,value); }
}
private static void OnTextChanged(DependencyObject sender,DependencyPropertyChangedEventArgs args)
{
ControlTextBox controlTextBox = sender as ControlTextBox;
controlTextBox.UpdateText(args);
}
private void UpdateText(DependencyPropertyChangedEventArgs args)
{
TextBox.Text = (string)args.NewValue;
}
}
使用控件的地方:
<controls:ControlTextBox Text="{Binding PersonModel.Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"/>
但是这样,在我使用控件的地方,绑定是通过单一方式完成的。如果绑定的属性被更改,我可以在文本框中看到它。 但是,如果我在textBox中写了一些新内容,则绑定的属性不会更改。
我还应该怎么做才能将textBox更改为binding属性?
解决方法
在ControlTextBox.xaml中使用RelativeSource
绑定:
<TextBox ...
Text="{Binding Text,RelativeSource={RelativeSource AncestorType=UserControl}}" />
并删除PropertyChangedCallback:
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register(nameof(Text),typeof(string),typeof(ControlTextBox));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty,value); }
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。