[英]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.