我在UserControl中创建了一个文本框, 我在UserControl中创建了一个属性, 我想将textbox文本属性绑定到在usercontrol中创建的属性。将文本框的DataContext设置为Silverlight中的当前类
问题是,我不知道如何在XAML中指定datacontext到当前类。
任何想法??谢谢
我在UserControl中创建了一个文本框, 我在UserControl中创建了一个属性, 我想将textbox文本属性绑定到在usercontrol中创建的属性。将文本框的DataContext设置为Silverlight中的当前类
问题是,我不知道如何在XAML中指定datacontext到当前类。
任何想法??谢谢
这将得到你在你的文本框中输入你的代码隐藏的属性。根据你项目的规模,我会考虑MVVM将代码推送到ViewModel,然后在UserControl中指定this.DataContext =你的ViewModel的一个实例。
的XAML:
<UserControl x:Class="SilverlightApplication1.MainPage"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<StackPanel>
<TextBox Text="{Binding Foo,Mode=TwoWay}"/>
<Button Content="Click" Click="Button_Click"/>
</StackPanel>
</UserControl>
代码背后:
public partial class MainPage : UserControl
{
public string Foo { get; set; }
public MainPage()
{
InitializeComponent();
this.DataContext = this;
}
}
我会在代码中创建绑定。假设您的文本框x:Name="MyTextBox"
也假定您已在用户控件上添加了依赖项属性(或至少一个标准属性INotifyPropertyChanged
实现),请求MyText
。
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
Binding binding = new Binding("MyText");
binding.Mode = BindingMode.TwoWay;
binding.Source = this;
MyText.SetBinding(TextBox.TextProperty, binding);
}
}
这会将UserControl的DataContext
属性保留为其他更典型的用途。