Tuesday, September 4, 2012

WPF Custom Control Dependacy Property Binding to Property

WPF Custom Control Dependacy Property Binding to Property

Just playing around with different types of bindings and having a property binding a Dependancy 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 Dependancy Property in the code behind.

Thanks.

Steve

Answers & Comments...

Answer: 1

What is the exact problem? Set DataContext of UserControl to code-behind, such as:

<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">  </UserControl> 
by : ChrisDDhttp://stackoverflow.com/users/930211




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog