向windows phone上的自定义控件添加绑定
本文关键字:自定义控件 添加 绑定 windows phone | 更新日期: 2023-09-27 18:12:30
我已经为一个项目创建了一个自定义图像按钮。这是基于https://code.msdn.microsoft.com/windowsapps/Custom-Image-Button-in-4b300b62提供的代码。
我已经调整了图像按钮以适应我的需要,它在设计器中看起来很好。但是,我正试图使用DependencyProperty将textblock绑定到视图模型。
按钮的内部是这样的
<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>
没什么了不起的,但是我需要的。
TextBlock依赖的代码如下所示
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));
}
}
(我得到不能从System. windows . bind转换到System. bind)。字符串错误,这段代码将编译,但在setter中给出一个空的ref. exception)
我这样做的正确的方式,我是否需要创建一个DependencyProperty,如果我试图绑定到一个命令,或者我可以直接使用
private ICommand command;
public ICommand Command
{
get
{
return command;
}
set
{
command = value;
command.Execute(value);
}
}
将setter设置为"normal",改为:
SetValue(TextDependencyProperty, txtHeading.GetType().GetProperty("System.String").GetValue(txtHeading, null));
使用:
SetValue(TextDependencyProperty, value);
给你的UserControl
一个名字:
<UserControl ... x:Name="thisControl">
在你的TextBlock
使用绑定到你的控制属性:
Text="{Binding Text, ElementName=thisControl}"