简体   繁体   中英

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

In the main XAML:

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

In 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 in the constructor is null ;

DataContext in the function WindowPattern_MouseClick is NOT null;

Why?

Because the DataContext has to be set. It's just a normal property.

Think about how you would set the DataContext on an object. You'd create the object first (thus running the entire constructor) then you'd set the DataContext property.

That's what the system is doing under the hood.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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