2011-03-30 102 views
3

我一直在閱讀很多教程,但不知何故,他們提到有關將屬性綁定到簡單整數的問題。將屬性綁定到一個整數

下面是設置:

我得到了一個用戶控制。 我想將「私人int大小」綁定到XAML文件中邊框的寬度。

最簡單的方法是什麼?

回答

5

你綁定什麼都用同樣的方法:

<Border BorderThickness="{Binding Size}"> 
private int _Size; 
public int Size 
{ 
    get { return _Size; } 
    set 
    { 
     _Size = value; 
     if (PropertyChanged != null) 
      PropertyChanged(this, new PropertyChangedEventArgs("Size"); 
    } 
} 

當然你的類必須實現INotifyPropertyChanged爲好。

+0

好,我這樣做,但它仍然抱怨說,它無法找到的PropertyChanged – Hedge 2011-03-30 15:00:51

+1

'公共類的MyUserControl:用戶控件,INotifyPropertyChanged的{' – user7116 2011-03-30 15:05:09

+1

您從用戶控件繼承,沒有實現。 INotifyPropertyChanged是一個接口,您可以根據需要實現多個接口。 – vcsjones 2011-03-30 15:05:27

1

另一種方式是聲明一個新依賴屬性和應用TemplateBinding

這裏是控制模板,在這裏我設置綁定Size屬性的寬度。

<Style TargetType="{x:Type local:MyUserControl}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type local:MyUserControl}"> 
       <Border Background="{TemplateBinding Background}" 
         BorderBrush="{TemplateBinding BorderBrush}" 
         BorderThickness="{TemplateBinding BorderThickness}"> 
        <TextBox Width="{TemplateBinding Size}"/> 
       </Border> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 



public class MyUserControl : Control 
{ 
    static MyUserControl() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(MyUserControl), new FrameworkPropertyMetadata(typeof(MyUserControl))); 
    } 

    public int Size 
    { 
     get { return (int)GetValue(SizeProperty); } 
     set { SetValue(SizeProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for Size. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty SizeProperty = 
     DependencyProperty.Register("Size", typeof(int), typeof(MyUserControl), new UIPropertyMetadata(20)); 
} 

參考Link

相關問題