这是如何实现的(如果我理解您的意思正确)。您有一个名为
MyControl
的用户控件。创建
MyControlView
视图。
<UserControl x:Class="Project.Controls.MyControlView"
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">
<Grid HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding LabelText}"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Margin="5,0"/>
<ComboBox Grid.Row="1"
ItemsSource="{Binding ComboBoxItems}"
SelectedItem="{Binding SelectedItem}"
HorizontalAlignment="Stretch"
Margin="0,0,5,0"/>
</Grid>
</UserControl>
现在视图模型将是:
public class MyControlViewModel
{
}
现在我们来讲解你可能感到困惑的那一点。如果我想在另一个视图中使用这个控件,比如称之为 BigView
,我可以这样做:
<Window x:Class="NameSpace.BigView"
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"
xmlns:Controls="clr-namespace:Project.Controls"> // Important reference to your control namespace.
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Controls:MyControlView Grid.Row="0" Margin="0,5"
DataContext="{Binding MyControlA}"/>
<Controls:MyControlView Grid.Row="1" Margin="0,5"
DataContext="{Binding MyControlB}"/>
</Grid>
</Window>
现在在视图模型
BigViewModel
中,您将拥有两个属性。
public RangeSliderControlViewModel MyControlA { get; set; }
public RangeSliderControlViewModel MyControlB { get; set; }
那么你可以通过
MyControlA.LabelText = "一些文本"
等方式访问每个控件的属性。请注意,在
BigViewModel
中,
MyControlA
/
MyControlB
不需要实现
INotifyPropertyChanged
,但是您控件中的属性必须这样做,以便更新能够向上传递并更新
BigView
。
希望这有所帮助。
RelativeSource = {RelativeSource Mode = FindAncestor,AncestorType = UserControl}
来绑定该属性。 - Clemens