简体   繁体   English

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

[英]MVVM: When DataContext is not null by using DataTemplate to bind viewmodel(DataContext) to the view

In the main XAML: 在主要的XAML中:

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

In Class GraphicEditorPropertyView.xaml.cs 在类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 in the constructor is null ; 构造函数中的 DataContextnull

DataContext in the function WindowPattern_MouseClick is NOT null; 函数WindowPattern_MouseClick中的DataContext 不为 null;

Why? 为什么?

Because the DataContext has to be set. 因为必须设置DataContext It's just a normal property. 这只是普通财产。

Think about how you would set the DataContext on an object. 想想将如何设置DataContext的对象上。 You'd create the object first (thus running the entire constructor) then you'd set the DataContext property. 首先创建对象(从而运行整个构造函数),然后设置DataContext属性。

That's what the system is doing under the hood. 这就是系统在后台执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM