我在使用WPF自定义控件方面遇到了一些问题,我试图让它工作但是却没有得到它:
这是我的问题,我正在创建一个简单的自定义控件,它与TextBox几乎相同。这个控件有一个名为“Texto”的依赖属性,XAML和自定义控件的反向代码之间的绑定工作正常,这里是代码:
<UserControl x:Class="WpfCustomControlLibrary1.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="47" d:DesignWidth="147">
<Grid Height="43" Width="142">
<TextBox Height="23" HorizontalAlignment="Left" Margin="12,8,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" Text="{Binding Texto}"/>
</Grid>
依赖属性代码:
public static readonly DependencyProperty TextoProperty = DependencyProperty.Register("Texto", typeof(string), typeof(UserControl1));
public string Texto
{
get
{
return (string)GetValue(TextoProperty);
}
set
{
SetValue(TextoProperty, value);
}
}
好的,现在问题是:当我在其他窗口中使用此控件时,我尝试将“Texto”属性绑定到viewmodel(就像其他所有内容一样简单),但视图模型上的属性不会改变:
ViewModel代码:
public class ViewModelTest
{
public string SomeText { get; set; }
}
应用程序窗口的代码:
public ViewModelTest test;
public Window1()
{
InitializeComponent();
}
private void button1_Click_1(object sender, RoutedEventArgs e)
{
MessageBox.Show(test.SomeText);
MessageBox.Show(uc.Texto);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
test = new ViewModelTest();
this.DataContext = test;
}
与视图模型的属性绑定:
<my:UserControl1 HorizontalAlignment="Left" Margin="27,12,0,0" Name="uc" VerticalAlignment="Top" Texto="{Binding Path=SomeText,Mode=TwoWay}"/>
为了让它更清楚,如果我在自定义控件中写“Hello”,然后我按下“button1”,第一条消息什么也没显示,第二条消息显示“Hello”。
你可以看到我对此很新,所以我希望你们中的一些人可以帮助我。感谢。
答案 0 :(得分:2)
您的绑定Texto="{Binding SomeText}"
工作正常,问题是从用户控件重新绑定到内部文本框。记住绑定将始终(如果没有修改)引用DataContext
。但是您的DataContext不包含Texto属性。你的控制就是这样,要引用你需要的东西叫TemplateBinding
,但这只适用于你在ControlTemplate中。哪个不是那么解决方案是什么?
您可以使用特殊形式的绑定,方法是将DataContext中的源更改为具有给定名称的控件:首先为UserControl命名
<UserControl x:Class="WpfCustomControlLibrary1.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"
x:Name="mainControl"
d:DesignHeight="47" d:DesignWidth="147">
现在将绑定更改为引用控件,而不是控件的DataContext。
<TextBox Text="{Binding ElementName=mainControl, Path=Texto}"/>
现在,您的ViewModel绑定到您的用户控件,用户控件的内容绑定到用户控件Texto属性。
另外一件小事,你称之为自定义控件,实际上是一个用户控件,自定义控件是其他东西。