我有一个用于用户控件的 View 模型,该 View 模型是在该 View 模型的数据模板中定义的。我想将usercontrol的'GridViewData'属性绑定(bind)到viewmodel的'Data'属性。
我对WPF还是很陌生,在绑定(bind)方面很糟糕,所以请客气:p
XAML:
<Window x:Class="ReportUtility.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:lite="clr-namespace:ReportUtility.Controls.LiteGrid"
xmlns:vm="clr-namespace:ReportUtility.ViewModels"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title="MainWindow" Height="350" Width="525">
<!--This is the view model I want to bind to variable name is Grid: hosted in the content control below-->
<Window.Resources>
<DataTemplate DataType="{x:Type vm:LiteGridViewModel}">
<lite:LiteGrid GridViewData="{Binding ??}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Content="TestButton" HorizontalAlignment="Stretch" Command="{Binding ExecuteQueryCommand}"/>
<TextBox Grid.Row="1" Text="{Binding Path=SqlCommandText, UpdateSourceTrigger=PropertyChanged}"/>
<ContentControl Content="{Binding Grid}" Grid.Row="2" Background="Red"/>
<Border Background="Aqua" Grid.Column="1" Grid.RowSpan="3"/>
<GridSplitter Grid.Column="0" Width="3" Grid.RowSpan="3"/>
</Grid>
最佳答案
您将绑定(bind)到Data
<DataTemplate DataType="{x:Type vm:LiteGridViewModel}">
<lite:LiteGrid GridViewData="{Binding Data}"/>
</DataTemplate>
最好在
LiteGrid
UserControl中进行此绑定(bind),而不是依赖使用控件设置值的XAML。<UserControl GridViewData="{Binding Data}">
...
</UserControl>
您的绑定(bind)始终引用当前对象的
DataContext
。由于您的DataTemplate
是LiteGridViewModel
类型的,因此该DataContext
中的DataTemplate
始终将是LiteGridViewModel
类型。例如,如果您有一个类似
public class MyClassA
{
MyClassB ClassB {get; set;}
}
public class MyClassB
{
MyClassC ClassC {get; set;}
}
还有
MyClassA ClassA
的ViewModel属性(这意味着您可以引用ClassA.ClassB.ClassC
),您可以执行以下操作<ContentControl Content="{Binding ClassA}">
<ContentControl Content="{Binding ClassB}"> <!-- DataContext is MyClassA -->
<ContentControl Content="{Binding ClassC}"> <!-- DataContext is MyClassB -->
<!-- DataContext is MyClassC -->
</ContentControl>
</ContentControl>
</ContentControl>
关于wpf - 与多个 View 模型绑定(bind),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7011875/