Custom Control Dependency Property Binding to Property - c#

Just playing around with different types of bindings and having a property binding a Dependency Property of my custom control to another property.
XAML:
<UserControl x:Class="BrickBreaker.Brick"
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"
d:DesignHeight="20" d:DesignWidth="50" >
<Rectangle Width="50" Height="20" RadiusX="3" RadiusY="3" Stroke="Black" Fill="{Binding BrickFill, Mode=TwoWay}" />
Code Behind:
public partial class Brick : UserControl
{
public Brick()
{
InitializeComponent();
}
public Brush BrickFill
{
get { return (Brush)GetValue(BrickFillProperty); }
set { SetValue(BrickFillProperty, value); }
}
// Using a DependencyProperty as the backing store for BrickFill. This enables animation, styling, binding, etc...
public static readonly DependencyProperty BrickFillProperty =
DependencyProperty.Register("BrickFill", typeof(Brush), typeof(Brick), null);
}
Implemenation In MainWindow.xaml
<UserControl x:Class="BrickBreaker.MainPage"
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:BrickBreaker="clr-namespace:BrickBreaker" mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
<Grid x:Name="LayoutRoot" Background="White">
<BrickBreaker:Brick Margin="100,100,0,0" BrickFill="Azure"/>
</Grid>
Basically I want to bind the Rectangles Fill Property to the Dependency Property in the code behind.
Thanks.
Steve

What is the exact problem? Set DataContext of UserControl to code-behind, such as:
<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
</UserControl>

Missing this: DataContext="{Binding RelativeSource={RelativeSource Self}}"

Related

How to bind a dependency property in XAML?

I have a user control in which I have defined a dependency property in its code-behind:
public static readonly DependencyProperty MyDependencyPropertyProperty = DependencyProperty.Register(
"MyDependencyProperty", typeof(MyType), typeof(MyView), new PropertyMetadata(null));
public MyType MyDependencyProperty
{
get
{
return (MyType)GetValue(MyDependencyPropertyProperty);
}
set
{
SetValue(MyDependencyPropertyProperty, value);
}
}
Now I want to bind this dependecy property in my view, to a property in my view model, something like this:
<UserControl x:Class="Myproject.Views.MyViewView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="1000"
**MyDependencyPropertyProperty {Binding MyPropetyInViewModel}**
Name="MyView">
This code is to give an idea about what I would like, to use the dependency property to set the binding.
Usually, you would set the dependency property, where you use your UserControl.
<MyViewView MyDependencyPropertyProperty="{Binding MyPropetyInViewModel}" />
If you really want to do that in the control itself, you could create a style to set the value.
<UserControl x:Class="Myproject.Views.MyViewView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
xmlns:local="clr-namespace:Myproject.Views"
mc:Ignorable="d"
d:DesignHeight="450"
d:DesignWidth="1000"
Name="MyView">
<UserControl.Style>
<Style>
<Setter Property="local:MyViewView.MyDependencyPropertyProperty" Value="{Binding MyPropetyInViewModel}"/>
</Style>
</UserControl.Style>
<!-- ...other markup -->
</UserControl>

C# WPF use properties from different usercontrol as Command parameter

I have a problem with referencing properties or elements on different user controls in my MVVM WPF application.
Edit: Reduced code to a MCVE (hopefully). Also removed PropertyChanged Events to reduce code.
TLDR
I split up all my MainWindow.xaml elements to different user controls
In the menubar (one control) I want to fire a ICommand to save a Settings object (which is the datacontext of the MainWindow
For the method that is called in the Command I need a value from a completely different UserControl that is neither parent nor child of the menubar
How can I retrieve the value from the PasswordBox in a MVVM approach (most preferably as the CommandParameter on the MenuBar)?
View
MainWindow.xaml
<Window x:Class="WpfApp1.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:ViewModel="clr-namespace:WpfApp1.ViewModel"
xmlns:View="clr-namespace:WpfApp1.View"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
<ViewModel:SettingsViewModel/>
</Window.DataContext>
<StackPanel>
<DockPanel>
<View:MenuBar DataContext="{Binding}"/>
</DockPanel>
<TabControl>
<TabItem Header="Tab1" DataContext="{Binding AppSettings}">
<View:TabItemContent/>
</TabItem>
</TabControl>
</StackPanel>
</Window>
The MenuBar which is supposed to bind on ICommand properties on the ViewModel (the DataContext of MainWindow).
MenuBar.xaml
<UserControl x:Class="WpfApp1.View.MenuBar"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1.View"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" >
<Menu DockPanel.Dock="Top" Height="Auto" >
<!-- In the command I need a reference to the password on the tabItem -->
<MenuItem Name="SaveItem" Height="Auto" Header="Save"
Command="{Binding SaveCommand}"
CommandParameter="Binding RelativeSource=
{RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"/>
</Menu>
</UserControl>
TabItemContent.xaml
<UserControl x:Class="WpfApp1.View.TabItemContent"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApp1.View"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800"
DataContext="{Binding PasswordSettings}">
<Grid>
<PasswordBox Height="25" Width="100" />
</Grid>
</UserControl>
In TabItemControl.xaml.cs I tried to introduce a Dependency Property and set the value to the datacontext of the control.
ViewModel
SettingViewModel.cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using WpfApp1.Commands;
using WpfApp1.Model;
namespace WpfApp1.ViewModel
{
public class SettingsViewModel
{
public Settings AppSettings { get; private set; } = new Settings();
public ICommand SaveCommand { get; private set; }
public SettingsViewModel()
{
SaveCommand = new DelegateCommand( SaveSettings );
// load settings and call
// OnPropertyChanged( "AppSettings" );
}
public void SaveSettings( object o = null )
{
if( o is string encryptedPass )
{
// get the password and save it to AppSettings object
}
// call save method on settings
}
}
}
Model (Setting classes)
AppSetting.cs (encapsulating all the setting objects from the other tabs)
namespace WpfApp1.Model
{
public class Settings
{
public PasswordSettings PwSettings { get; set; } = new PasswordSettings();
}
}
PasswordSettings.cs
namespace WpfApp1.Model
{
public class PasswordSettings
{
public string EncryptedPass { get; set; }
}
}
and finally the DelegateCommand implementation in
DelegateCommand.cs see this gist

Get property value WPF

I am trying get a value from a property but isn't working I always get a null value.
string imageNormal;
public static readonly DependencyProperty ImageNormalProperty =
DependencyProperty.Register("ImageNormal", typeof(string), typeof(MainWindow));
public string ImageNormal
{
get { return (string)GetValue(ImageNormalProperty); }
set { SetValue(ImageNormalProperty, value); }
}
public ButtonImageStyle()
{
InitializeComponent();
DataContext = this;
Console.WriteLine("Path: " + ImageNormal);
}
Xaml ButtonImageStyle.xaml:
<Image Source="{Binding ImageNormal}" Stretch="None" HorizontalAlignment="Center" VerticalAlignment="Center" />
Xaml MainWindow.xaml:
<local:ButtonImageStyle HorizontalAlignment="Left" Height="60" VerticalAlignment="Top" Width="88" ImageNormal="C:/Users/Xafi/Desktop/add.png"/>
I always obtain next output:
Path:
since your ImageSource is have to be binded to it's parent DependencyProperty (which is defined to your code behind), you have to define your binding to be rlative to your UserControl (let's name it This). Thus please try to change your xaml in the next way:
Xaml code
<UserControl x:Class="SomeBindingExampleSOHelpAttempt.ButtonImageStyle"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" x:Name="This">
<Grid>
<Image Source="{Binding ElementName=This, Path=ImageNormal, UpdateSourceTrigger=PropertyChanged}"
Stretch="None" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid></UserControl>
Here you can find an additional perfect answer.
Regards.

Multiple Instances of UserControl not Binding

Hi I tried to create a simple UserControl with TestValue1 and TestValue2 Properties and Created two Instances of it in a stack panel. But what is happening is that only the Last Control is storing the values in the User Control the rest have just blank values.
Here is the XAML code where they are used:
<userControls:TestControl TestValue1="Vasu" TestValue2="Mahesh"></userControls:TestControl>
<userControls:TestControl TestValue1="Test" TestValue2="Testing2"></userControls:TestControl>
Here is the UserControl's XAML and Code Behind:
Code Behind:
public sealed partial class TestControl : UserControl
{
public TestControl()
{
this.InitializeComponent();
this.DataContext = this;
}
public readonly DependencyProperty TestValue1DependencyProperty = DependencyProperty.Register("TestValue1", typeof(string), typeof(TestControl), new PropertyMetadata(default(string)));
public string TestValue1
{
get
{
return (string)GetValue(TestValue1DependencyProperty);
}
set
{
SetValue(TestValue1DependencyProperty, value);
}
}
public readonly DependencyProperty TestValue2DependencyProperty = DependencyProperty.Register("TestValue2", typeof(string), typeof(TestControl), new PropertyMetadata(default(string)));
public string TestValue2
{
get
{
return (string)GetValue(TestValue2DependencyProperty);
}
set
{
SetValue(TestValue2DependencyProperty, value);
}
}
}
XAML File:
<UserControl
x:Name="TestControlName"
x:Class="downloader.UserControls.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:downloader.UserControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding TestValue1 , ElementName=TestControlName}"></TextBlock>
<TextBlock Text="{Binding TestValue2 , ElementName=TestControlName}"></TextBlock>
</StackPanel>
</Grid>
</UserControl>
Solved!
The Trick was with the DataContext :
in the XAML of the UserControl I set up:
<UserControl
x:Name="TestControlName"
x:Class="downloader.UserControls.TestControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:downloader.UserControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid x:Name="LayoutRootGrid">
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding TestValue1}"></TextBlock>
<TextBlock Text="{Binding TestValue2}"></TextBlock>
</StackPanel>
</Grid>
</UserControl>
And in C# Code Behind:
//this.DataContext = this;
LayoutRootGrid.DataContext = this;
Probably because the DataContext was being Overridden by this ... Since DataContext is inherited from the Parent , by using the old line it was no longer inheriting from its parent.
So I gave the inner element the data context of the code behind which allowed the UserControl to inherit the DataContext of the Parent (i.e. from where it is called)

Custom dependency property binding

I got some problem with custom dependency property binding.
We have:
Custom user control with one dependency property and binding to self:
<UserControl x:Class="WpfApplication1.SomeUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<Grid>
<Label>
<Label.Template>
<ControlTemplate>
<Label Content="{Binding MyTest}"/>
</ControlTemplate>
</Label.Template>
</Label>
</Grid>
... and code of control:
public partial class SomeUserControl : UserControl
{
public SomeUserControl()
{
InitializeComponent();
}
public static readonly DependencyProperty MyTestProperty = DependencyProperty.Register("MyTest", typeof(int), typeof(SomeUserControl));
public int MyTest
{
get { return (int)GetValue(MyTestProperty); }
set { SetValue(MyTestProperty, value); }
}
}
I trying to use this control with binding to some simple property of simple model class:
<UserControl x:Class="WpfApplication1.AnotherUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:wpfApplication1="clr-namespace:WpfApplication1"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" DataContext="{Binding RelativeSource={RelativeSource Mode=Self}}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<wpfApplication1:SomeUserControl MyTest="{Binding Path=Model.MyNum}" Grid.Column="0"/>
<Label Content="{Binding Path=Model.MyNum}" Grid.Column="1"/>
</Grid>
... with code
public partial class AnotherUserControl : UserControl
{
public MyModel Model { get; set; }
public AnotherUserControl()
{
Model = new MyModel();
Model.MyNum = 1231;
InitializeComponent();
}
}
... and model:
public class MyModel:INotifyPropertyChanged
{
private int _myNum;
public int MyNum
{
get { return _myNum; }
set { _myNum = value; OnPropertyChanged("MyNum");}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
But binding is not working. Stack have no errors in compilation. Now, binding working with statndart wpf label control (with same model), and don't working with my custom control and custom property. Please help me to understand reasons of this problem and solve it;
Thanks)
You should use ElementName Binding in your SomeUserControl.
<UserControl x:Class="WpfApplication1.SomeUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
x:Name="uc">
<Grid>
<Label>
<Label.Template>
<ControlTemplate>
<Label Content="{Binding MyTest, ElementName=uc}"/>
</ControlTemplate>
</Label.Template>
</Label>
</Grid>
here some more information why you should not set the datacontext of a usercontrol to self/this.
Data Binding in WPF User Controls
You will need to update your binding as below i.e you will have to bind to the ancestor usercontrol property using RelativeSource as you are setting the DataContext of child usercontrol explicitly, default binding will search for path inside the child userControl's DataContext.
<wpfApplication1:SomeUserControl MyTest="{Binding Path=DataContext.Model.MyNum, RelativeSource={RelativeSource FindAncestor={x:Type UserControl}}}" Grid.Column="0"/>

Categories