我有一个用于viewcontrol的viewmodel,它在viewmodel的数据模板中定义。我想将usercontrol的'GridViewData'属性绑定到viewmodel的'Data'属性。
我还是WPF的新手并且在绑定方面很糟糕,所以请善待: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>
答案 0 :(得分:4)
您将绑定到Data
<DataTemplate DataType="{x:Type vm:LiteGridViewModel}">
<lite:LiteGrid GridViewData="{Binding Data}"/>
</DataTemplate>
在LiteGrid
UserControl中执行此绑定甚至更好,而不是依赖于使用该控件设置值的XAML。
<UserControl GridViewData="{Binding Data}">
...
</UserControl>
您的绑定始终引用当前对象的DataContext
。由于DataTemplate
适用于LiteGridViewModel
类型,因此DataContext
中的DataTemplate
始终属于LiteGridViewModel
类型。
例如,如果您有类似
的类public class MyClassA
{
MyClassB ClassB {get; set;}
}
public class MyClassB
{
MyClassC ClassC {get; set;}
}
ViewModel属性MyClassA ClassA
(意思是你可以引用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>