WPF converter implied in custom control? - wpf

In my WPF Custom Control which draws a pie chart, I successfully made it draw a pie chart given a set of values in a string, for example "10 20 30" would draw a pie chart with correct proportions. I bound the DrawingImage's drawing property to a converter to convert from the string into a DrawingGroup. This worked great, but I am trying to bypass the need for a converter.
Here is my MainWindow:
<Grid Margin="10">
<local:PieChart DrawingCode="289 666 1337 780" Width="400" Height="400" RingWidth="300" Background="White" />
</Grid>
Here is my template for the custom control:
<Style TargetType="{x:Type local:PieChart}">
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:PieChart}">
<Grid>
<Image Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
<Image.Source>
<DrawingImage Drawing="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DrawingCode}" />
</Image.Source>
</Image>
<Ellipse Width="{TemplateBinding RingWidth}" Height="{TemplateBinding RingWidth}" Fill="{TemplateBinding Background}" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And finally, here is my attempt at the Custom Control class:
public class PieChart : Control
{
public static readonly DependencyProperty DrawingCodeProperty = DependencyProperty.Register("DrawingCode", typeof(string), typeof(PieChart), new UIPropertyMetadata(null));
public static readonly DependencyProperty RingWidthProperty = DependencyProperty.Register("RingWidth", typeof(double), typeof(PieChart), new UIPropertyMetadata(null));
static PieChart()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(PieChart), new FrameworkPropertyMetadata(typeof(PieChart)));
}
public string DrawingCode
{
get { return DrawingCodeConverter((string)GetValue(DrawingCodeProperty)); }
set { SetValue(DrawingCodeProperty, value); }
}
public double RingWidth
{
get { return (double)GetValue(RingWidthProperty); }
set { SetValue(RingWidthProperty, this.Width - value); }
}
public DrawingGroup DrawingCodeConverter(string value)
{
// This converter works but is long so I removed it from the post.
}
}
I am pretty sure the problem is somewhere in the data types I should be using. Also, if there is a completely different way to do this that I am ignorant of, please let me know. Also note that RingWidth is not the problem, it is DrawingCode.

The getter and setter of the CLR wrapper of a dependency property may be bypassed when the property is accessed in XAML or by a Binding, Style Setter, Animation, etc. WPF then calls GetValue and SetValue directly. The reason is explained in XAML Loading and Dependency Properties
You must therefore not call anything else than GetValue and SetValue in the getter and setter. Instead, declare your dependency property with a PropertyChangedCallback like this:
public static readonly DependencyProperty DrawingCodeProperty =
DependencyProperty.Register(
"DrawingCode",
typeof(string),
typeof(PieChart),
new FrameworkPropertyMetadata(DrawingCodePropertyChanged));
public string DrawingCode
{
get { return (string)GetValue(DrawingCodeProperty); }
set { SetValue(DrawingCodeProperty, value); }
}
private static void DrawingCodePropertyChanged(
DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var pieChart = (PieChart)o;
pieChart.SetDrawingCode((string)e.NewValue);
}
private void SetDrawingCode(string drawingCode)
{
var drawingGroup = DrawingCodeConverter(drawingCode);
// do something with drawingGroup
}

Related

Send Value from View Model to UserControl Dependency Property WPF

I have a dependency property in a UserControl with a property called SelectedColor. From my main app, the view of the window that uses this my code is:
<controls:ColorPicker SelectedColor="{Binding MyCanvas.CanvasBackgroundColor}" />
And the code from the view model is:
public MyCanvas { get; set; }
public MyWindowViewModel(MyCanvas myCanvas)
{
MyCanvas = myCanvas;
}
And then the XAML for my UserControl is:
<UserControl . . .>
<Button Click="Button_Click">
<Button.Style>
<Setter Property="Background" Value="Transparent" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{Binding SelectedColor}" BorderBrush="Black" BorderThickness="1" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
</UserControl>
And the code-behind:
public ColorPicker()
{
InitializeComponent();
DataContext = this;
}
public SolidColorBrush SelectedColor
{
get { return (SolidColorBrush)GetValue(SelectedColorProperty); }
set { SetValue(SelectedColorProperty, value); }
}
public static readonly DependencyProperty SelectedColorProperty =
DependencyProperty.Register(nameof(SelectedColor), typeof(SolidColorBrush), new UIPropertyMetadata(null));
I think the problem might be with the line in the code-behind DataContext = this;. Is it correct that declaring this creates an entirely new context for the instance of this user control in the main app and therefore any values sent to it from the view model would be re-initialized? If so, how can I send the value over without it being re-declared? I also need the DataContext = this line because without it some functionality within my UserControl will no longer work.
Has anyone encountered this before?
Thanks in advance!
DataContext = this sets the DataContext of the UserControl to itself. You don't want to do this. Instead you could bind to a property of the UserControl using a {RelativeSource} without setting the DataContext property:
<Border Background="{Binding SelectedColor, RelativeSource={RelativeSource AncestorType=UserControl}}"
BorderBrush="Black" BorderThickness="1" />
Code-behind:
public ColorPicker()
{
InitializeComponent();
}
public SolidColorBrush SelectedColor
{
get { return (SolidColorBrush)GetValue(SelectedColorProperty); }
set { SetValue(SelectedColorProperty, value); }
}
public static readonly DependencyProperty SelectedColorProperty =
DependencyProperty.Register(nameof(SelectedColor), typeof(SolidColorBrush), new UIPropertyMetadata(null));

Binding to readonly property in generic.xaml for customControl (Button)

I'm doing a CustomControl (button) using generic.xaml and dependency properties.
Here is my generic.xaml code :
<Style TargetType="{x:Type local:FlatButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:FlatButton}">
<Grid MinHeight="50" MaxHeight="50" MinWidth="200" MaxWidth="200">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="3*" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Background="{TemplateBinding BackgroundDarker}">
</Grid>
<Grid Grid.Column="1" Background="{TemplateBinding Background}">
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Segoe UI" Foreground="White" FontWeight="Bold" />
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
My customControl class :
Public Shared Shadows BackgroundProperty As DependencyProperty = DependencyProperty.Register("Background", GetType(SolidColorBrush), GetType(FlatButton))
Public Overloads Property Background As SolidColorBrush
Get
Return CType(GetValue(BackgroundProperty), SolidColorBrush)
End Get
Set(value As SolidColorBrush)
SetValue(BackgroundProperty, value)
End Set
End Property
Public Shared BackgroundDarkerProperty As DependencyProperty = DependencyProperty.Register("BackgroundDarker", GetType(SolidColorBrush), GetType(FlatButton))
Public ReadOnly Property BackgroundDarker As SolidColorBrush
Get
Return Background.Darker
End Get
End Property
And finally how I use my control in a UserControl :
<Grid>
<local:FlatButton Background="Red" />
</Grid>
When I put "Red" in the xaml of my FlatButton, the right part is well colored in Red (in VS and in runtime), but what I want is that the left part colores itself automatically with Darker red (it's an extension which works). But it seems not to be colored. I've no binding error in output.
What am I doing wrong ?
Thanks all.
-----EDIT----- :
Ok, to do that I made a converter which convert the "Background" value to a darker color.
I templateBinded the background of the left grid to "Background" with an instance of my converter.
While a converter will work, this functionality belongs inside the FlatButton control code. Use the Background's PropertyChangedCallback to update BackgroundDarker.
public class FlatButton : Button
{
// Background
public static new DependencyProperty BackgroundProperty = DependencyProperty.Register("Background", typeof(SolidColorBrush), typeof(FlatButton), new PropertyMetadata(OnBackgroundChanged));
public new SolidColorBrush Background { get { return (SolidColorBrush)GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } }
// BackgroundDarker
public static DependencyProperty BackgroundDarkerProperty = DependencyProperty.Register("BackgroundDarker", typeof(SolidColorBrush), typeof(FlatButton));
public SolidColorBrush BackgroundDarker { get { return (SolidColorBrush)GetValue(BackgroundDarkerProperty); } private set { SetValue(BackgroundDarkerProperty, value); } }
private static void OnBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// update BackgroundDarker
var btn = (FlatButton)d;
btn.BackgroundDarker = btn.Background.Darker();
}
static FlatButton()
{
// lookless control, get default style from generic.xaml
DefaultStyleKeyProperty.OverrideMetadata(typeof(FlatButton), new FrameworkPropertyMetadata(typeof(FlatButton)));
}
}
public static class SolidColorBrushExtension
{
public static SolidColorBrush Darker(this SolidColorBrush brush)
{
const double perc = 0.6;
return new SolidColorBrush(Color.FromRgb((byte)(brush.Color.R * perc), (byte)(brush.Color.G * perc), (byte)(brush.Color.B * perc)));
}
}

WPF - Selector - Custom Control - SelectionChanged Event Not Firing

I am new to custom control creation. I have laid some groundwork for a new custom control based on the Selector class. My understanding was that I should use this class since I needed the control to have an Items collection and the ability to handle selections. I believe that changing the ItemTemplate may have overriden some of this ability because I do not receive the SelectionChanged event at the control level or application level. I would think if I'm right that there is some sort of SelectionRegion XAML tag that I can put the DataTemplate innards into. I have not had luck in finding anything like this. After looking through Google for a while, I am ready to just ask. What am I missing? Below is the ItemTemplate markup. Thanks for any help. Thanks even more if you can tell me why the Text in TextBlock is enclosed in parentheses even though the data isn't.
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1">
<TextBlock Text="{Binding}" Foreground="Black" Background="White" MinHeight="12" MinWidth="50"/>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
At the request of a commenter, here is the complete XAML for the control so far:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SourceMedicalWPFCustomControlLibrary">
<Style TargetType="{x:Type local:MultiStateSelectionGrid}">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1">
<TextBlock Text="{Binding Code}" Foreground="Black" Background="White" MinHeight="12" MinWidth="50" Padding="2" ToolTip="{Binding Description}"/>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MultiStateSelectionGrid}">
<StackPanel HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,0,0,0" Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,0,0,0" Content="{TemplateBinding Content}"/>
<ItemsPresenter/>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
And the anemic code-behind as well:
namespace SourceMedicalWPFCustomControlLibrary
{
public class MultiStateSelectionGridState
{
public Brush Background { get; set; }
public Brush Foreground { get; set; }
public Brush Border { get; set; }
public string Text { get; set; }
public MultiStateSelectionGridState()
{
Background = Brushes.White;
Foreground = Brushes.Black;
Border = Brushes.Black;
Text = String.Empty;
}
};
public class MultiStateSelectionGrid : Selector
{
public static readonly DependencyProperty ContentProperty =
DependencyProperty.Register("Content", typeof(object), typeof(MultiStateSelectionGrid),
new FrameworkPropertyMetadata(null,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsParentMeasure));
public object Content
{
get { return (object)GetValue(ContentProperty); }
set { SetValue(ContentProperty, value); }
}
public static readonly DependencyProperty StatesProperty =
DependencyProperty.Register("States", typeof(List<MultiStateSelectionGridState>), typeof(MultiStateSelectionGrid),
new FrameworkPropertyMetadata(new List<MultiStateSelectionGridState>(),
FrameworkPropertyMetadataOptions.AffectsRender));
public List<MultiStateSelectionGridState> States
{
get { return (List<MultiStateSelectionGridState>)GetValue(StatesProperty); }
set { SetValue(StatesProperty, value); }
}
static MultiStateSelectionGrid()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MultiStateSelectionGrid), new FrameworkPropertyMetadata(typeof(MultiStateSelectionGrid)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
this.SelectionChanged += new SelectionChangedEventHandler(MultiStateSelectionGrid_SelectionChanged);
}
void MultiStateSelectionGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show("Hi");
}
}
}
here is what I do. I use the apply template function of the custom control and add a handlerto the selection chnaged event of the control I want.
simple sample here:
public event EventHandler<SelectionChangedEventArgs> YourControlSelectionChanged;
private void Selector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListSelectionChanged != null) {
ListSelectionChanged(sender, e);
}
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
//find or declare your control here, the x:name in xaml should be YourControl
YourControl== this.Template.FindName("YourControl", this) as YourControlType
YourControl.SelectionChanged += ResultListBox_SelectionChanged;
}
you can then bind to the name of the public event (YourControlSelectionChanged) you declared in your custom control class in xaml.
hope this helps.
From reading some full code examples of different controls, I believe my answer is that I am doing this all wrong. Instead, I need to have control that has a Selector like a ListBox in the ControlTemplate. THEN, #JKing 's advice would help me get to where I need to be. The answer to the actual question asked though is the aforementioned change from using Selector as a base class to having a selector in the template for the control. Thanks for the help.

databinding on a user control only working partially (silverlight)

I am not sure what I am doing wrong here. I spent a good hour last night to figure it out, maybe I am just dumb.
I created this user control to display a bordered text, which uses data binding to fill the style and the text.
This is how I call it from the main page:
<mynamespace:BorderedText x:Name="DateTime"
Grid.Column="1"
Grid.Row="0"
BorderStyle="{StaticResource borderStyle}"
LabelStyle="{StaticResource labelStyle}"
TextStyle="{StaticResource valueStyle}"
Label="Current Date/Time"
Text="N/A" />
The control is pretty simple:
<UserControl x:Class="MyNamespace.BorderedText"
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="480"
d:DesignWidth="480">
<Grid>
<Border Name="border" Style="{Binding BorderStyle}">
<StackPanel>
<TextBlock Style="{Binding LabelStyle}"
Text="{Binding Label}" />
<TextBlock Style="{Binding TextStyle}"
Text="{Binding Text}" />
</StackPanel>
</Border>
</Grid>
The problem is that all data binding works, except for the Border data binding. I also tried to data bind the background or any other property, without success.
Code behind has the DependencyProperty properties set up and that’s it. Note that the DataContext for data binding is set up in the constructor. Tried to assign it to the Grid or to the Border itself, without success.
Does anybody have any clue or see something big I am missing here?
namespace MyNamespace
{
public partial class BorderedText : UserControl
{
public static readonly DependencyProperty LabelProperty = DependencyProperty.Register("Label", typeof(string), typeof(BorderedText), new PropertyMetadata(null));
public static readonly DependencyProperty LabelStyleProperty = DependencyProperty.Register("LabelStyle", typeof(Style), typeof(BorderedText), new PropertyMetadata(null));
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(BorderedText), new PropertyMetadata(null));
public static readonly DependencyProperty TextStyleProperty = DependencyProperty.Register("TextStyle", typeof(Style), typeof(BorderedText), new PropertyMetadata(null));
public static readonly DependencyProperty BorderStyleProperty = DependencyProperty.Register("BorderStyle", typeof(Style), typeof(BorderedText), new PropertyMetadata(null));
public BorderedText()
{
InitializeComponent();
((Grid)this.Content).DataContext = this;
//((Border)this.Content).DataContext = this;
}
public string Label
{
set { SetValue(LabelProperty, value); }
get { return (string)GetValue(LabelProperty); }
}
public Style LabelStyle
{
set { SetValue(LabelStyleProperty, value); }
get { return (Style)GetValue(LabelStyleProperty); }
}
public string Text
{
set { SetValue(TextProperty, value); }
get { return (string)GetValue(TextProperty); }
}
public Style TextStyle
{
set { SetValue(TextStyleProperty, value); }
get { return (Style)GetValue(TextStyleProperty); }
}
public Style BorderStyle
{
set { SetValue(BorderStyleProperty, value); }
get { return (Style)GetValue(BorderStyleProperty); }
}
}
}
---- UPDATE:
It turned out to be something completely different and unrelated to databinding which is properly wired...
In the borderStyle I was using this syntax for a background property:
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush>
<SolidColorBrush.Color>
<Color>
<Color.A>
100
</Color.A>
<Color.R>#95</Color.R>
<Color.B>#ED</Color.B>
</Color>
</SolidColorBrush.Color>
</SolidColorBrush>
</Setter.Value>
</Setter>
which apparently works in the designer but not in the phone.
Changing it to:
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="#649500ED" />
</Setter.Value>
</Setter>
Solved the problem
Well, you forgot one thing... the DataContext of the Border!
Give your UserControl a name, and then you can add to your binding something like:
<TextBox Text="{Binding Path=MyText, ElementName=UserControlRoot}" />
this will work (at least it worked for me in WPF, heh)

Dependency property not working, trying to set through style setter

I am trying to set up a custom style for my newly made usercontrol, however i am getting the error : "Cannot convert the value in attribute 'Property' to object of type 'System.Windows.DependencyProperty'."
I thought i had set up Dependency properties but it seemed this was not the case, so i did some research and added:
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(BitmapSource), typeof(Image));
to make this:
-- MyButton.Xaml.Cs --
namespace Client.Usercontrols
{
public partial class MyButton : UserControl
{
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(BitmapSource), typeof(Image));
public MyButton()
{
InitializeComponent();
}
public event RoutedEventHandler Click;
void onButtonClick(object sender, RoutedEventArgs e)
{
if (this.Click != null)
this.Click(this, e);
}
BitmapSource _imageSource;
public BitmapSource ImageSource
{
get { return _imageSource; }
set
{
_imageSource = value;
tehImage.Source = _imageSource;
}
}
}
}
This unfortunately does not work. I also tried this:
public BitmapSource ImageSource
{
get { return (BitmapSource)GetValue(MyButton.ImageSourceProperty); }
set
{
SetValue(ImageSourceProperty, value);
}
}
But that did not work and the image was not shown and generated the same error as mentioned previously anyway.
Any ideas?
Regards Kohan.
-- MyButton.Xaml --
<UserControl x:Class="Client.Usercontrols.MyButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinHeight="30" MinWidth="40"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Button Width="Auto" HorizontalAlignment="Center" Click="onButtonClick">
<Border CornerRadius="5" BorderThickness="1" BorderBrush="Transparent" >
<Grid>
<Image Name="tehImage" Source="{Binding ImageSource}" />
<TextBlock Name="tehText" Text="{Binding Text}" Style="{DynamicResource ButtonText}" />
</Grid>
</Border>
</Button>
</UserControl>
-- MYButton Style --
<Style TargetType="{x:Type my:MyButton}" >
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type my:MyButton}">
<ContentPresenter />
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="ImageSource" Value="../Images/Disabled.png" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Biggest problem I see is that you're registering the property as owned by Image rather than by your UserControl. Change to:
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource", typeof(BitmapSource), typeof(MyButton));
If that doesn't work, will need to see your XAML.
The standard form for a dependency property is (i've added in your information):
public BitmapSource ImageSource
{
get { return (BitmapSource)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
/* Using a DependencyProperty as the backing store for ImageSource.
This enables animation, styling, binding, etc... */
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource",
typeof(BitmapSource),
typeof(MyButton),
new UIPropertyMetadata(null)
);
it seems like your also trying to pass through the dependency property to the ImageSource of the object called "tehImage". You can set this up to automatically update using the PropertyChangedCallback... this means that whenever the property is updated, this will call the update automatically.
thus the property code becomes:
public BitmapSource ImageSource
{
get { return (BitmapSource)GetValue(ImageSourceProperty); }
set { SetValue(ImageSourceProperty, value); }
}
/* Using a DependencyProperty as the backing store for ImageSource.
This enables animation, styling, binding, etc... */
public static readonly DependencyProperty ImageSourceProperty =
DependencyProperty.Register("ImageSource",
typeof(BitmapSource), typeof(MyButton),
new UIPropertyMetadata(null,
ImageSource_PropertyChanged
)
);
private static void ImageSource_PropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
((MyButton)source).tehImage.ImageSource = (ImageSource)e.NewValue
}
Hopefully with the correctly registered dependency property, this will help you narrow down the issue (or even fix it)
Set the DataContext for your UserControl:
public MyButton()
{
InitializeComponent();
DataContext = this;
}
Alternatively, if you can't do that (since the DataContext is set to another object, for example), you can do this in your XAML:
<UserControl x:Class="Client.Usercontrols.MyButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinHeight="30" MinWidth="40"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
x:Name="MyControl">
<Button Width="Auto" HorizontalAlignment="Center" Click="onButtonClick">
<Border CornerRadius="5" BorderThickness="1" BorderBrush="Transparent" >
<Grid>
<Image Name="tehImage" Source="{Binding ElementName=MyControl, Path=ImageSource}" />
<TextBlock Name="tehText" Text="{Binding ElementName=MyControl, Path=Text}" Style="{DynamicResource ButtonText}" />
</Grid>
</Border>
</Button>
</UserControl>
The correct way of implementing a source for an Image in a user control in my opinion is not BitmapSouce. The easiest and best way (according to me again) is using Uri.
Change your dependency property to this (while also defining a change callback event):
ImageSourceProperty = DependencyProperty.Register(
"ImageSource", typeof (Uri), typeof (MyButton),
new FrameworkPropertyMetadata(new PropertyChangedCallback(OnImageSourceChanged)));
and the property to this:
public Uri ImageSource
{
get
{
return (Uri)GetValue(ImageSourceProperty);
}
set
{
SetValue(ImageSourceProperty, value);
}
}
Where your call back is like this:
private static void OnImageSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
MyButton hsb = (MyButton)sender;
Image image = hsb.tehImage;
image.Source = new BitmapImage((Uri) e.NewValue);
}

Resources