I have two UI controls whose properties I want to bind to properties of two different objects. Here is my XAML file:
<Window x:Class="WpfBindingDemo.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"
mc:Ignorable="d" SizeToContent="WidthAndHeight" ResizeMode="CanMinimize">
<Canvas Width="300" Height="200">
<Slider x:Name="_slider1" Canvas.Left="10" Canvas.Top="10" Width="272"/>
<Slider x:Name="_slider2" Canvas.Left="10" Canvas.Top="36" Width="272"/>
</Canvas>
</Window>
And here is my code behind:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace WpfBindingDemo
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Binding binding1 = new Binding("MyProperty1");
binding1.Mode = BindingMode.TwoWay;
binding1.Source = _myObject1;
BindingOperations.SetBinding(_slider1, Slider.ValueProperty, binding1);
Binding binding2 = new Binding("MyProperty2");
binding2.Mode = BindingMode.TwoWay;
binding2.Source = _myObject1;
BindingOperations.SetBinding(_slider2, Slider.ValueProperty, binding2);
}
MyClass1 _myObject1 = new MyClass1();
MyClass2 _myObject2 = new MyClass2();
}
public class MyClass1 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }
public double MyProperty1 {get; set}
}
public class MyClass2 : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); }
public double MyProperty2 {get; set}
}
}
As you can see, I bind UI control properties (Value
in this case) to different objects properties in code (in window constructor) and it works all right, but I find this declaration too bulky and I don't like that it's divided in two parts. I wonder if there is more compact way to declare this kind of binding in XAML, something like
<Slider x:Name="_slider1" Value="{Binding MyProperty1, Source=_myObject1}"/>
<Slider x:Name="_slider2" Value="{Binding MyProperty2, Source=_myObject2}"/>
I've tried to play with Source
, RelativeSource
and ElementName
properties, but failed to make it work. Am I missing something?