M.A*_*zad 2 c# wpf user-controls mvvm
我有一个像这样的UserControl:
<UserControl x:Class="MySample.customtextbox"
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="20" d:DesignWidth="300">
<Grid>
<TextBox x:Name="Ytextbox" Background="Yellow"/>
</Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)
我希望在mvvm模式中使用我的控件...我想我可以将我的viewmodel中的属性绑定到Ytextbox Text属性
<CT:customtextbox ?(Ytextbox)Text ="{binding mypropertyinviewmodel}"/>
Run Code Online (Sandbox Code Playgroud)
...我该怎么做?
您应该在UserControl上创建一个属性,并将其内部绑定到TextBox的文本.
即
<UserControl Name="control" ...>
<!-- ... -->
<TextBox Text="{Binding Text, ElementName=control}"
Background="Yellow"/>
Run Code Online (Sandbox Code Playgroud)
public class customtextbox : UserControl
{
public static readonly DependencyProperty TextProperty =
TextBox.TextProperty.AddOwner(typeof(customtextbox));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
<CT:customtextbox Text="{Binding mypropertyinviewmodel}"/>
Run Code Online (Sandbox Code Playgroud)
(不要将UserControl中的DataContext设置为自身,除非您希望所有期望继承DataContext的外部绑定失败,使用ElementName或RelativeSource用于内部绑定)