I have created a custom image button for a project. This is based on the code provided at https://code.msdn.microsoft.com/windowsapps/Custom-Image-Button-in-4b300b62 .
I've adjusted the image button to suit my needs and it looks fine in the designer. However, I'm trying to bind the textblocks to a view model using a DependencyProperty.
The guts of the button looks like this
<StackPanel x:Name="Panel" Orientation="Horizontal" VerticalAlignment="Center">
<Image Margin="10,0,-10,0" x:Name="Image" Width="48" Height="48" Source="/Assets/Images/mappin.png"/>
<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Width="400" x:Name="txtHeading" Text="Mooo" Grid.Row="0" TextAlignment="Center" Margin="20,0,-10,0" FontFamily="/TfL.CongestionCharge.WindowsPhone;component/Assets/Fonts/NJFont-Book.ttf#NJFont Book" />
</Grid>
</StackPanel>
</StackPanel>
Nothing amazing, but does what I need.
The code behind for the TextBlock dependency looks like this
public static readonly DependencyProperty TextDependencyProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(UserControl),
new PropertyMetadata(null));
public string Text
{
get
{
return GetValue(TextDependencyProperty) as string;
}
set
{
SetValue(TextDependencyProperty, txtHeading.GetType().GetProperty("System.String").GetValue(txtHeading, null));
}
}
(I was getting could not convert from a System.Windows.Bindable to System.String error originally, this code will compile but gives a null ref. exception in the setter)
Am I going about this the correct way and do I need to create a DependencyProperty if I try to bind to an ICommand or can I just use
private ICommand command;
public ICommand Command
{
get
{
return command;
}
set
{
command = value;
command.Execute(value);
}
}
Change your setter to be "normal" one, instead:
SetValue(TextDependencyProperty, txtHeading.GetType().GetProperty("System.String").GetValue(txtHeading, null));
Use this:
SetValue(TextDependencyProperty, value);
Give your UserControl
a name:
<UserControl ... x:Name="thisControl">
In your TextBlock
use a binding to your control property:
Text="{Binding Text, ElementName=thisControl}"
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.