2013-03-11 62 views
1

如何在代碼中設置樣式的屬性值?我有一個資源詞典,我想在代碼中改變一些屬性,我該怎麼辦?如何在代碼中設置屬性值?

的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; 
... 

什麼,我做錯了什麼?

+0

嗯,怎麼了?你目前的執行情況如何,以致你不滿意? – DHN 2013-03-11 09:34:53

回答

1

當您運行代碼時,您還沒有解釋發生了什麼(或不發生)。但是,您發佈的代碼正在創建new Setter(...),但不會顯示您正在使用它做什麼。您需要將創建的setter添加到樣式中才能生效。

但是,在您引用的樣式的Xaml中,已經有一個setter屬性用於width屬性。所以,我懷疑你實際上是想編輯現有的setter,而不是創建一個新的setter。

+0

我只是想改變width屬性的值,在同一resourcedicionary我有一個文本塊和更改文本,這樣做: 的WPF代碼: 2013-03-11 10:14:19

+0

正如我所說的那樣不改變寬度並設置最大容器 – 2013-03-11 10:23:21

0

爲什麼不在XAML中創建按鈕,然後實現INotifyPropertyChanged-接口並在代碼中爲「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」時都會自動更新。你需要設置屬性,而不是私有變量本身。否則,它不會觸發其更新事件,並且您的按鈕不會更改。

+0

如果所討論的風格在整個應用程序中共享,那麼這將不太容易工作 - 您必須傳遞任何類實現該屬性的相同實例圍繞應用程序中的每個窗口(或潛在的UserControl),或者將其公開爲靜態。 – 2013-03-11 11:35:54