1

コードでスタイルのプロパティ値を設定する方法は? resourcedictionary があり、コード内のいくつかのプロパティを変更したいのですが、どうすればよいですか?

wpf コード:

<ResourceDictionary 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Style
        x:Key="ButtonKeyStyle"
        TargetType="{x:Type Button}">

        <Setter Property="Width" Value="{Binding MyWidth}"/>
        ....

C# コード:

Button bt_key = new Button();
bt_key.SetResourceReference(Control.StyleProperty, "ButtonKeyStyle");
var setter = new Setter(Button.WidthProperty, new Binding("MyWidth"));
setter.Value = 100;
...

私は何を間違っていますか?

4

2 に答える 2

1

コードを実行したときに何が起こっているか (またはしていないか) を説明していません。ただし、投稿したコードは作成してnew Setter(...)いますが、それで何をしているのかを示していません。効果を得るには、作成したセッターをスタイルに追加する必要があります。

ただし、参照しているスタイルの Xaml には幅プロパティのセッターが既にあります。したがって、新しいセッターを作成するのではなく、既存のセッターを実際に編集したいのではないかと思います。

于 2013-03-11T09:40:44.060 に答える
0

XAML でボタンを作成してから、INotifyPropertyChanged-Interface を実装し、コード内に "MyWidth" のプロパティを作成してみませんか? 次のようになります。

XAML:

<Button Name="MyButton" Width="{Bindind Path=MyWidth}" />

ビューモデル/分離コード:

// This is your private variable and its public property
private double _myWidth;
public double MyWidth
{
    get { return _myWidth; }
    set { SetField(ref _myWidth, value, "MyWidth"); } // You could use "set { _myWidth = value; RaisePropertyChanged("MyWidth"); }", but this is cleaner. See SetField<T>() method below.
}

// Feel free to add as much properties as you need and bind them. Examples:
private double _myHeight;
public double MyHeight
{
    get { return _myHeight; }
    set { SetField(ref _myHeight, value, "MyHeight"); }
}

private string _myText;
public double MyText
{
    get { return _myText; }
    set { SetField(ref _myText, value, "MyText"); }
}

// This is the implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(String propertyName)
{
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

// Prevents your code from accidentially running into an infinite loop in certain cases
protected bool SetField<T>(ref T field, T value, string propertyName)
{
    if (EqualityComparer<T>.Default.Equals(field, value))
            return false;

    field = value;
    RaisePropertyChanged(propertyName);
    return true;
}

次に、ボタンの幅プロパティをこの「MyWidth」プロパティにバインドすると、コードで「MyWidth」を設定するたびに自動的に更新されます。プライベート変数自体ではなく、プロパティを設定する必要があります。そうしないと、更新イベントが発生せず、ボタンが変更されません。

于 2013-03-11T11:15:36.457 に答える