MVVM:当DataConmplate不为null时,使用DataTemplate将viewmodel(DataContext)绑定到视图

时间:2014-05-20 14:40:32

标签: c# wpf mvvm

在主XAML中:

<DataTemplate DataType="{x:Type vm:GraphicEditorPropertyViewModel}">
    <views:GraphicEditorPropertyView/>
</DataTemplate>

在Class GraphicEditorPropertyView.xaml.cs

public partial class GraphicEditorPropertyView : UserControl
{
    private bool SecurityLevelBar_MouseCaptured = false;

    public GraphicEditorPropertyView()
    {
        InitializeComponent();

        Int32 pattern = ((GraphicEditorPropertyViewModel)(this.DataContext)).CurrentGraphicEditorVgProperty.Pattern;
        UInt32 frontColor = ((GraphicEditorPropertyViewModel)(this.DataContext)).CurrentGraphicEditorVgProperty.FrontColor;
        UInt32 backColor = ((GraphicEditorPropertyViewModel)(this.DataContext)).CurrentGraphicEditorVgProperty.BackColor;
        ConvertPattern2BrushCanvas convertPattern2BrushCanvas = new ConvertPattern2BrushCanvas(((GraphicEditorPropertyViewModel)(this.DataContext)).Parent.CurrentLibDiagramDesigner);
        Brush brush = convertPattern2BrushCanvas.Convert(new object[] { frontColor, backColor, pattern }, null, null, null) as Brush;

        Selected_Pattern.Fill = brush;
    }

    private void WindowPattern_MouseClick(object sender, RoutedEventArgs e)
    {
        Button button = sender as Button;
        Brush buttonBrush = button.Background;
        Selected_Pattern.Fill = buttonBrush;

        ((GraphicEditorPropertyViewModel)(this.DataContext)).CurrentGraphicEditorVgProperty.Pattern = System.Convert.ToInt32(button.ToolTip.ToString());
    }
}

}

构造函数中的

DataContext null ;

函数 WindowPattern_MouseClick 中的

DataContext NOT null;

为什么?

1 个答案:

答案 0 :(得分:0)

因为必须设置DataContext。这只是一个普通的财产。

考虑如何在对象上设置DataContext。您首先创建对象(从而运行整个构造函数),然后设置DataContext属性。

这就是系统在幕后做的事情。