[英]Adding binding to a custom control on windows phone
我为项目创建了一个自定义图像按钮。 这基于https://code.msdn.microsoft.com/windowsapps/Custom-Image-Button-in-4b300b62提供的代码。
我已经调整了图像按钮以适合我的需求,并且在设计器中看起来不错。 但是,我试图使用DependencyProperty将文本块绑定到视图模型。
按钮的内胆看起来像这样
<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.Bindable转换为System.String错误,此代码将编译,但在setter中提供空引用异常。)
我要使用正确的方法吗?如果我尝试绑定到ICommand,还是需要使用DependencyProperty?
private ICommand command;
public ICommand Command
{
get
{
return command;
}
set
{
command = value;
command.Execute(value);
}
}
将您的设置员更改为“正常”设置,而不是:
SetValue(TextDependencyProperty, txtHeading.GetType().GetProperty("System.String").GetValue(txtHeading, null));
用这个:
SetValue(TextDependencyProperty, value);
为您的UserControl
命名:
<UserControl ... x:Name="thisControl">
在TextBlock
使用对控件属性的绑定:
Text="{Binding Text, ElementName=thisControl}"
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.