2016-10-14 12 views
0

ボタンに基づいてカスタムコントロールを作成しています。ボタンの幅をクラスのプロパティにバインドします。私はthisthis、およびthisを見ましたが、それらは私が探しているものではなく、動作しません。プロパティをカスタムコントロールの別のプロパティにバインドします。

Generic.xaml

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:local="clr-namespace:CustomControl"> 

<Style TargetType="{x:Type local:MyCustomControl}" BasedOn = "{StaticResource {x:Type Button}}"> 
    <Setter Property = "Background" Value = "LightSalmon" /> 
    <Setter Property = "Foreground" Value = "Blue"/> 
    <Setter Property = "Height" Value = "50"/> 
    <Setter Property = "Width" Value = "{Binding MyCustomControl.TextBinding}"/> 
    <Setter Property = "VerticalAlignment" Value = "Top"/> 
    <Setter Property = "Margin" Value="10"/> 
</Style> 

</ResourceDictionary> 

MyCustomControl.cs

namespace CustomControl 
{ 
public class MyCustomControl : Button 
{ 
    double m_textBinding = 50; 
    public double TextBinding 
    { 
     get { return m_textBinding; } 
     set { m_textBinding = value; } 
    } 
    static MyCustomControl() 
    { 
     DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), 
      new FrameworkPropertyMetadata(typeof(MyCustomControl))); 
    } 
} 
} 

必要であれば、私は "セッター" 機能を使用することができ、かつ、手動"Width = value;"を指定するが、私は使用することを好みます拘束力。現在、"{Binding MyCustomControl.TextBinding}"は機能していません。

+0

を 'TextBinding'は、コントロールの幅を定義するプロパティの奇妙な名前のようです。 – Clemens

+0

雅、私はそれが文字列ではなく二重であることを実感しました。私は怠惰なので名前をつけただけです。これは単なるテストです。 –

答えて

1

これは動作するはずです:

<Setter Property="Width" 
     Value="{Binding TextBinding, RelativeSource={RelativeSource Self}}"/> 
+0

それはちょっと働いた。初期値は50ですが、私のコントロールを使用すると、MainWindowコードビハインドで、 'myControl.TextBinding = 100;と言うと何も起こりません。 –

+0

これは、プロパティが値の変更について通知しないためです。どちらかを依存関係プロパティにするか、INotifyPropertyChangedインターフェイスを実装します。依存性プロパティは、UIコントロールで優先されます。 – Clemens

+0

ああ、ありがとう。私はそれらをしなければならなかったことを忘れた。私はDependencyプロパティを作成しましたが、ほぼ完璧に動作しています。その秋の価値を今すぐ​​働かせるだけです。もう一度、ありがとう! –

関連する問題