.net 将usercontrol上的绑定设置为mainwindow';视图模型
我有以下用户控件.net 将usercontrol上的绑定设置为mainwindow';视图模型,.net,wpf,xaml,mvvm,data-binding,.net,Wpf,Xaml,Mvvm,Data Binding,我有以下用户控件 <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:
<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>
如何将“PartNumberTextBox”从UserControl数据绑定到此属性
谢谢
"{Binding DataContext.SelectedRefDesFilter,
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
这应该可以工作,但我不知道UserControl中的属性将绑定到窗口中现有的属性。绑定语法应该有效。在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 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}}}" />
在您的视图中,只需将此新文本属性绑定到现有的SelectedRefDesFilter属性
<controls:FilterTraceDataControl Grid.Row="1" Visibility="{Binding FilterBarVisible ,Converter={StaticResource BooleanToVisibilityConverter}, Mode=TwoWay}"
Text="{Binding SelectedRefDesFilter, Mode=TwoWay}" />
非常感谢您的帮助。
<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}}}" />
<controls:FilterTraceDataControl Grid.Row="1" Visibility="{Binding FilterBarVisible ,Converter={StaticResource BooleanToVisibilityConverter}, Mode=TwoWay}"
Text="{Binding SelectedRefDesFilter, Mode=TwoWay}" />