In this minimal example view and view model are the same class MainWindow
, so the DataContext
is set to this
inside the constructor. Usually it should be the view model in a MVVM architecture.
XAML:
<Window x:Class="PlotTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:oxyplot="http://oxyplot.org/wpf"
mc:Ignorable="d"
Title="MainWindow"
Height="450"
Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox x:Name="HeightTextBox"
Width="200"
TextChanged="HeightTextBox_TextChanged" />
<oxyplot:PlotView Grid.Row="1"
Model="{Binding MyModel, UpdateSourceTrigger=PropertyChanged}"
Height="{Binding ModelHeight, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</Window>
Code behind:
using OxyPlot;
using System.ComponentModel;
using System.Windows;
namespace PlotTest
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
private double modelheight = 300;
public MainWindow()
{
this.DataContext = this;
this.MyModel = new PlotModel() { Background = OxyColors.AliceBlue };
InitializeComponent();
}
public event PropertyChangedEventHandler PropertyChanged;
public double ModelHeight
{
get { return modelheight; }
private set
{
modelheight = value;
this.RaisePropertyChanged("ModelHeight");
}
}
public PlotModel MyModel { get; private set; }
private void HeightTextBox_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
{
if (double.TryParse(this.HeightTextBox.Text, out double height))
{
this.ModelHeight = height;
}
}
private void RaisePropertyChanged(string propertyName = "")
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}