2013-03-11 4 views
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; 
... 

?

+0

흠, 무엇이 잘못 되었나요? 현재의 구현은 무엇 때문에 만족스럽지 않은가? WPF 코드 : DHN

답변

1

코드를 실행할 때 발생하는 현상 (또는 발생하지 않은 현상)을 설명하지 않았습니다. 그러나 게시 한 코드는 new Setter(...)을 작성하고 있지만 수행중인 내용은 표시하지 않습니다. 생성 된 세터를 스타일에 추가하여 효과를 나타낼 필요가 있습니다.

그러나 참조하는 스타일의 Xaml에는 width 속성에 대한 설정자가 이미 있습니다. 그래서, 당신은 실제로 새로운 것을 만드는 것보다 기존의 세터를 편집하고 싶다고 생각합니다.

+0

난 그냥 내가 TextBlock의를 가지고 텍스트를 변경 같은 resourcedicionary에, width 속성의 값을 변경, 그렇게 할 콘텐츠} " ... C# 코드 : 문자열 키; bt_key.Content = key; ... 나는 setter의 값으로 동일하게하고 싶다. –

+0

내가 말한대로 너비를 변경하지 않고 최대 컨테이너를 설정합니다. –

0

XAML에 단추를 만든 다음 INotifyPropertyChanged -Interface를 구현하고 코드에서 "MyWidth"속성을 만드는 이유는 무엇입니까? 그것은 다음과 같이 수 :

XAML :

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

뷰 모델/Codebehind가 : 그런 다음이 "MyWidth"-property과에 버튼의 폭-속성을 바인딩 할 수 있습니다

// 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"를 설정할 때마다 자동으로 업데이트됩니다. 개인 변수 자체가 아니라 속성을 설정해야합니다. 그렇지 않으면 업데이트 이벤트가 발생하지 않으며 버튼이 변경되지 않습니다.

+0

문제의 스타일이 애플리케이션에서 공유되는 경우 쉽게 작동하지 않습니다. 클래스를 구현하는 모든 클래스의 동일한 인스턴스를 전달해야합니다. 응용 프로그램의 모든 윈도우 (또는 잠재적으로 UserControl) 주위에 배치하거나 정적으로 표시합니다. –

관련 문제