Binding 如何在窗口中创建ControlTemplate的两个独立实例?
我有一个controltemplate,带有一个文本框和一个按钮,该按钮打开一个子表单来选择一些内容,并在文本框中显示所选项目,如下所示:Binding 如何在窗口中创建ControlTemplate的两个独立实例?,binding,mvvm,mvvm-light,controltemplate,Binding,Mvvm,Mvvm Light,Controltemplate,我有一个controltemplate,带有一个文本框和一个按钮,该按钮打开一个子表单来选择一些内容,并在文本框中显示所选项目,如下所示: <Window.Resources> <ControlTemplate x:Key="CreateParam"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Wi
<Window.Resources>
<ControlTemplate x:Key="CreateParam">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<Button Content="select" Command="{Binding ShowSpecItemViewommand}" Grid.Column="0" Margin="2"/>
<TextBox Margin="2" Text="{Binding Param}" Grid.Row="0" Grid.Column="1"/>
<TextBlock Margin="5" Text="patameter" Grid.Row="0" Grid.Column="2"/>
</Grid>
</ControlTemplate>
</Window.Resources>
public string param;
public string Param
{
get
{
return param;
}
set
{
param = value;
RaisePropertyChanged("Param");
}
}
现在我想在一个窗口中创建该控件的两个独立实例,但当我为第一个实例选择一个值时,它们都已更改。我应该定义两个属性吗?我如何将它们绑定到控件模板?
我不确定每个人都能理解我的意思,所以我希望有人能编辑我的问题:如何使用控件模板?您将此模板附加到哪个控件?它是您拥有的自定义控件的模板吗?它是已知控件的模板吗 如何实例化控件模板的DataContext 虽然您可以使用ControlTemplate和自定义控件实现所需的功能,并且如果您有很多控件(即两个以上),并且对象的所有实例都可以使用ControlTemplate,那么使用DataTemplate或UserControl会更好。要实现您想要的目标,有多种方法,但下面的代码被视为标准解决方案: 假设Param是MyVM对象的属性。那么您的XAML文件应该是:
<Window
x:Class="SO.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:so="clr-namespace:SO"
Height="200" Width="350"
Title="SO Sample"
>
<Window.Resources>
<DataTemplate DataType="{x:Type so:MyVM}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<Button Content="select" Command="{Binding ShowSpecItemViewommand}" Grid.Column="0" Margin="2"/>
<TextBox Margin="2" Text="{Binding Param}" Grid.Row="0" Grid.Column="1"/>
<TextBlock Margin="5" Text="patameter" Grid.Row="0" Grid.Column="2"/>
</Grid>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ContentControl>
<so:MyVM Param="1234" />
</ContentControl>
<ContentControl>
<so:MyVM Param="5678" />
</ContentControl>
</StackPanel>
</Window>