Yup, it's possible, and even what I'd consider to be fundamental in WPF development. It's called data binding. I'll be implementing a simple one way data binding here which binds to a property on the code behind file (i.e MainView.xaml
binds to MainView.xaml.cs
), but you can bind to any class you'd like, this then forms the fundamentals of MVVM.
Xaml:
<Window x:Class="MainView"
Title="MainView"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<!-- Snip -->
</Window>
The important part is DataContext="{Binding RelativeSource={RelativeSource Self}}
. Right here we're telling the window to bind to itself (i.e the code behind file). This is required for anything to work. You can use this Q&A to see how to bind to something else.
Continuing on:
<wf:NumericUpDown Maximum="{Binding Max}" Minimum="{Binding Min}" />
Here we're telling the NumericUpDown
component to get its Maximum
and Minimum
values from the data context. Now, one caveat, you can only bind to properties and nothing else. So, if you ever run into a problem where your bindings aren't working, check to see if you're binding to a property or not. Here's the code of code behind file
public class MainWindow
{
public int Max { get; } = 12000;
public int Min { get; } = 120;
public MainWindow()
{
InitializeComponent();
}
}
This is a one way data binding, i.e the XAML can only read these values. For things like an input box, you'll need to use TwoWay bindings. And if anything changes those values (currently impossible, but may be in the future), then you need to implement INotifyPropertyChanged
P.S: No guarantees for the code. I just typed it out in this text box without any auto complete and the last time I did WPF is quite a while ago. Just leave a comment if something doesn't work and I'll try my best to fix it