为了简单起见,我制作了以下用户控件:
XAML:
<UserControl x:Class="Ex2.testUC"
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"
xmlns:local="clr-namespace:Ex2"
x:Name="testuc"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel>
<TextBox Text="{Binding Path=MyText, ElementName=testuc}" />
</StackPanel>
</UserControl>
CS.XAML:
using System.Windows;
using System.Windows.Controls;
namespace Ex2
{
public partial class testUC : UserControl
{
public testUC()
{
InitializeComponent();
}
public string MyText
{
get { return (string)GetValue(MyTextProperty); }
set { SetValue(MyTextProperty, value); }
}
public static readonly DependencyProperty MyTextProperty =
DependencyProperty.Register("MyText", typeof(string), typeof(testUC));
}
}
现在我已经将他插入到带有简单 View 模型的 View 中:
XAML:
<Window x:Class="Ex2.testWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Ex2"
xmlns:control="clr-namespace:Ex2"
mc:Ignorable="d"
Title="testWindow" Height="300" Width="300">
<StackPanel>
<control:testUC MyText="{Binding Path=Text}"/>
<Button Height="100" Click="Button_Click" Content="CLICK HERE"/>
<Label x:Name="lbl" Height="50"/>
</StackPanel>
</Window>
XAML.CS:
using System.Windows;
namespace Ex2
{
public partial class testWindow : Window
{
private testVMText vm;
public testWindow()
{
InitializeComponent();
vm = new testVMText();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
lbl.Content = vm.Text;
}
}
}
查看模型:
using System.ComponentModel;
namespace Ex2
{
class testVMText : INotifyPropertyChanged
{
public string Text { get; set; }
public testVMText()
{
Text = "default";
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
当我单击按钮时,我希望打印 View 模型中的文本值。
我的目的是将用户控件文本的文本框绑定(bind)到 View 模型中的 Text 属性。但是,当我更改文本框中的文本并单击按钮时,始终会打印字符串“default”。
我在这里做错了什么?
最佳答案
将Binding
的模式设置为TwoWay
:
<local:testUC MyText="{Binding Path=Text, Mode=TwoWay}"/>
当您在 testUC
类中注册依赖项属性时,您还可以将 BindsTwoWayByDefault
属性设置为 true:
public static readonly DependencyProperty MyTextProperty =
DependencyProperty.Register("MyText", typeof(string), typeof(testUC), new FrameworkPropertyMetadata() { BindsTwoWayByDefault = true });
关于c# - 绑定(bind)用户控件以查看模型属性时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44131577/