Reputation: 1465
I'm trying to bind value from ViewModel class to custom property declared in code behind Window class. What I'm getting with this example is "The member 'FullScreen' is not recognized or is not accessible." error.
Here is MainWindow class:
public partial class MainWindow : Window
{
public static readonly DependencyProperty FullScreenProperty =
DependencyProperty.Register(nameof(FullScreen), typeof(bool),
typeof(MainWindow), new PropertyMetadata(default(bool), PropertyChangedCallback));
public bool FullScreen
{
get => (bool)GetValue(FullScreenProperty);
set => SetValue(FullScreenProperty, value);
}
private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var value = (bool)e.NewValue;
//this.GoToFullScreen(value);
}
public MainWindow()
{
InitializeComponent();
}
}
And the XAML part:
<Window x:Class="WindowDependencyPropertyTest.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:local="clr-namespace:WindowDependencyPropertyTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" FullScreen="{Binding FullScreenFromVm}" >
<Grid>
</Grid>
</Window>
What would be the best way to achieve this functionality?
Upvotes: 0
Views: 794
Reputation: 21969
You can create a custom window and add dependency property to it
public class CustomWindow : Window
{
// propdp FullScreenFromVm ...
}
Then you just need to change
<Window ... >
to
<local:CustomWindow ... FullScreen="{Binding FullScreenFromVm}">
and change base class of window
public partial class MainWindow : CustomWindow
{
...
}
This way dependency property is available in xaml.
Initially I thought you could just write <local:MainWindow ...>
to get access to defined dependency property, but unfortunately this breaks code generation, because x:Class
expects the containing type to be a base class.
Upvotes: 1
Reputation: 128013
Provided that the MainWindow's DataContext
is set to an object with a FullScreenFromVm
property, this should work:
<Window x:Class="WindowDependencyPropertyTest.MainWindow" ...>
<Window.Style>
<Style>
<Setter Property="local:MainWindow.FullScreen"
Value="{Binding FullScreenFromVm}"/>
</Style>
</Window.Style>
...
</Window>
Or you bind the property in the MainWindow constructor:
public MainWindow()
{
InitializeComponent();
SetBinding(FullScreenProperty, new Binding("FullScreenFromVm"));
}
Upvotes: 1