2012-11-03 102 views
1

我需要一個數字控制到我的Windows手機應用程序。如何將控件的屬性綁定到控件元素的屬性?

我嘗試創建一個自定義控件,但我無法將控件的屬性綁定到控件的元素。

我又增加了一個依賴屬性來控制

public static readonly DependencyProperty LineThicknessProperty = 
      DependencyProperty.Register("LineThickness", typeof (double), typeof (DigitControl), new PropertyMetadata(default(double))); 

[DefaultValue(10D)] 
public double LineThickness 
{ 
    get { return (double) GetValue(LineThicknessProperty); } 
    set { SetValue(LineThicknessProperty, value); } 
} 

,並試圖將其綁定到該控件的元素

<UserControl x:Class="Library.DigitControl" 
    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" 
    FontFamily="{StaticResource PhoneFontFamilyNormal}" 
    FontSize="{StaticResource PhoneFontSizeNormal}" 
    Foreground="{StaticResource PhoneForegroundBrush}" 
    d:DesignHeight="480" d:DesignWidth="480"> 

    <Grid x:Name="LayoutRoot"> 
    <Rectangle Margin="0" StrokeThickness="0" Width="{Binding LineThickness, RelativeSource={RelativeSource Self}}" Fill="#FFFF5454" RadiusX="5" RadiusY="5"/> 
    </Grid> 
</UserControl> 

但它不工作。是在哪種方式將該屬性綁定到元素的屬性?

回答

1

在後面的代碼中執行此操作。在代碼

<Rectangle x:Name="theRect" Margin="0" StrokeThickness="0" Fill="#FFFF5454" RadiusX="5" RadiusY="5"/> 

那麼後面:

設置一個名稱

theRect.SetBinding(Rectangle.WidthProperty, new Binding("LineThickness"){Source = this}); 

在不使用Visual Studio的PC,所以applogies如果不是100%可編譯!但給你的一般想法。

+0

我已經通過這種方式解決了這個問題 –

0

你所做的不會工作,因爲RelativeSource={RelativeSource Self}將源設置爲目標對象,這是您的情況中的矩形。

由於矩形沒有LineThickness屬性,綁定失敗。

爲了獲得正確的綁定,你可以做幾件事情。

更好的方法可能是在您的UserControl構造函數中設置this.DataContext = this;,然後在XAML中簡單地將綁定設置爲Width="{Binding LineThickness}"

或者你可以針對用戶控件類型的最接近的元素,找到一個屬性,如果你不喜歡設置的DataContext:

Width="{Binding LineThickness, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" 

更新
你也可以簡單的給UserControl的名稱,並在綁定中將其與ElementName屬性進行引用:

<UserControl x:Name="uc1" ... </UserControl> 

Width="{Binding LineThickness, ElementName=uc1}" 
+0

不幸的是我無法使用FindAncestor,它不支持windows phone。 –

+0

好吧,但你可以使用DataContext解決方案嗎? –

+0

不,它可以解決目前的問題,但會出生很多新的 –

相關問題