3

私は基本的にデモを行っているので、理由を聞かないでください。

XAMLを使用してバインドするのは非常に簡単です。

c#コード:

public class MyData
    {
        public static string _ColorName= "Red";

        public string ColorName
        {
            get
            {
                _ColorName = "Red";
                return _ColorName;
            }
        }
    }

XAMLコード:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:c="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <c:MyData x:Key="myDataSource"/>
    </Window.Resources>

    <Window.DataContext>
        <Binding Source="{StaticResource myDataSource}"/>
    </Window.DataContext>

    <Grid>
        <Button Background="{Binding Path=ColorName}"
          Width="250" Height="30">I am bound to be RED!</Button>
    </Grid>
</Window>

しかし、私は同じバインディングを達成しようとしています。c#setBinding()関数を使用します。

        void createBinding()
        {
            MyData mydata = new MyData();
            Binding binding = new Binding("Value");
            binding.Source = mydata.ColorName;
            this.button1.setBinding(Button.Background, binding);//PROBLEM HERE             
        }

setBindingの最初のパラメータはDependencyプロパティですが、Backgroundはそうではないため、問題は最後の行にあります...したがって、ここでButtonクラスに適切なDependencyプロパティを見つけることができません

        this.button1.setBinding(Button.Background, binding);//PROBLEM HERE             

ただし、依存関係プロパティがあるため、TextBlockでも同様のことが簡単に実現できます。

  myText.SetBinding(TextBlock.TextProperty, myBinding);

誰かが私のデモを手伝ってくれますか?

4

1 に答える 1

2

2つの問題があります。

1)BackgroundPropertyは、バインディングのためにアクセスできる静的フィールドです。

2)さらに、バインディングオブジェクトを作成するときに、渡す文字列はプロパティの名前です。バインディング「ソース」は、このプロパティを含むクラスです。binding( "Value")を使用して文字列プロパティを渡すことにより、文字列の値を取得していました。この場合、MyDataクラスのColorプロパティ(Brush)を取得する必要があります。

コードを次のように変更します。

MyData mydata = new MyData();
Binding binding = new Binding("Color");
binding.Source = mydata;
this.button1.SetBinding(Button.BackgroundProperty, binding);

MyDataクラスにBrushプロパティを追加します。

public class MyData
{
    public static Brush _Color = Brushes.Red;
    public Brush Color
    {
        get
        {
            return _Color;
        }
    }
}
于 2012-06-14T16:49:28.660 に答える