Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a custom dependency property defined in code-behind from XAML

Is it possible to call a custom dependency property in the XAML of the element in which it is defined?

I mean, i have the following simple code for my mainWindow:

Code

public partial class MainWindow : Window
{

    public static readonly DependencyProperty SpecialToProperty =   DependencyProperty.Register("SpecialTo", typeof(double), typeof(MainWindow));

    public MainWindow()
    {

        InitializeComponent();

    }

    public double SpecialTo
    {
        get
        {
            return (double)GetValue(SpecialToProperty);
        }
        set
        {
            SetValue(DoubleAnimation.ToProperty, value);
        }
    }
}

How can i use that dependency property from the XAML partial code of the MainWindow class?

I mean something like:

<Window x:Class="WpfAnimationTEst.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"        
    SpecialTo=200>

I know it can be done using attached dependency properties, but is it the only way? Is it not possible to call a dependency property defined in the code-behind?

Thank you and sorry if the question is some kind of stupid, i'm just learning and trying to understand WPF.

like image 444
MorgoZ Avatar asked Sep 28 '22 19:09

MorgoZ


1 Answers

I found the answer after I initially posted a wrong answer:
The problem really lies in circular dependencies if you use andreask's answer. I had to create a BaseClass for all windows:
1) Create a new Window Base Class:

public class BaseWindow : Window {
    public BaseWindow() { }

    public static readonly DependencyProperty SpecialToProperty = DependencyProperty.Register("SpecialTo", typeof(double), typeof(BaseWindow));

    public double SpecialTo {
        get {
            return (double)GetValue(SpecialToProperty);
        }
        set {
            SetValue(SpecialToProperty, value);
        }
    }
}

This will be the new baseclass for all your windows.
2) Modify your MainWindow xaml:
(Change YOURNAMESPACE (2x) to your namespace name)

<local:BaseWindow x:Class="YOURNAMESPACE.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:YOURNAMESPACE"
        Title="MainWindow" Height="350" Width="525" SpecialTo="100">
    <Grid>

    </Grid>
</local:BaseWindow>

3) And you also need to modify your partial MainWindow.cs:

 public partial class MainWindow : BaseWindow {
        public MainWindow() {
            InitializeComponent();
        }
    }

That worked for me, however, you will always need to use the extra xaml markup in your window declaration.

like image 160
Noel Widmer Avatar answered Dec 31 '22 21:12

Noel Widmer