我有以下用户控制
<UserControl x:Class="Station.Controls.FilterTraceDataControl"
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">
<TextBox x:Name="PartNumbTextBox" Width="120" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0,0,0" Height="25"/>
</UserControl>
我在主窗口中使用它:
<Window
xmlns:controls="clr-namespace:Station.Controls"
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"
x:Class="Station.MainWindow"
Title="{Binding ApplicationTitle}" MinHeight="550" MinWidth="850" Height="650" Width="900"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<controls:FilterTraceDataControl Grid.Row="1" Visibility="{Binding FilterBarVisible ,Converter={StaticResource BooleanToVisibilityConverter}, Mode=TwoWay}"/>
</Window>
Window的Mainview具有以下属性:
public string SelectedRefDesFilter
{
get { return _selectedRefDesFilter; }
set
{
_selectedRefDesFilter = value;
RaisePropertyChanged("SelectedRefDesFilter");
}
}
我如何数据绑定&#34; PartNumbTextBox&#34;从UserControl到此属性。
感谢。
答案 0 :(得分:1)
在UserControl的代码隐藏(FilterTraceDataControl.xaml.cs)上,添加一个DependencyProperty,如下所示:
public string Text
{
get { return (string)this.GetValue(TextProperty); }
set { this.SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text", typeof(string), typeof(FilterTraceDataControl),new PropertyMetadata(null));
然后通过RelativeSource或ElementName将UserControl的TextBox绑定到它:
<TextBox x:Name="PartNumbTextBox" Width="120" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="5,0,0,0" Height="25"
Text="{Binding Text, RelativeSource={RelativeSource AncestorType={x:Type controls:FilterTraceDataControl}}}" />
在您的视图中,只需将此新Text属性绑定到现有的SelectedRefDesFilter属性。
<controls:FilterTraceDataControl Grid.Row="1" Visibility="{Binding FilterBarVisible ,Converter={StaticResource BooleanToVisibilityConverter}, Mode=TwoWay}"
Text="{Binding SelectedRefDesFilter, Mode=TwoWay}" />
答案 1 :(得分:0)
"{Binding DataContext.SelectedRefDesFilter,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
这应该可行,但我不知道UserControl中的属性是否与Windows中存在的属性有关。绑定语法应该有效。