2014-12-03 77 views
0

我有代碼:綁定值不正常工作

<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background). (GradientBrush.GradientStops)[1].(GradientStop.Color)" Storyboard.TargetName="grid"> 
    <EasingColorKeyFrame KeyTime="0:0:0.5" Value="{Binding CorBackground}"/> 
</ColorAnimationUsingKeyFrames> 

顏色值定義爲Value="#FFFFFF",我會想使用綁定來定義這個顏色。 Value="{Binding CorBackground}。這是可能的?

我創建一個MainWindow.xaml.cs財產,但不工作:

private string _corBackground = string.Empty; 
public string CorBackground 
{ 
    get { return _corBackground; } 
    set { _corBackground = value; } 
} 

回答

2

如果你不想使用MVVM模式與適當的結合,一個可能的解決方案是使用DependecyProperty在您的UserControl中(如在示例中稱爲「BackgroundColor」的SolidColorBrush屬性)。你MainWindow.cs會是什麼樣子

public partial class MainWindow : Window 
{ 
    public static readonly DependencyProperty BackgroundColorProperty = DependencyProperty.Register(
     "BackgroundColor", typeof (SolidColorBrush), typeof (MainWindow), new PropertyMetadata(default(SolidColorBrush))); 

    public SolidColorBrush BackgroundColor 
    { 
     get { return (SolidColorBrush) GetValue(BackgroundColorProperty); } 
     set { SetValue(BackgroundColorProperty, value); } 
    } 

    public MainWindow() 
    { 
     BackgroundColor = new SolidColorBrush(Colors.LightBlue); 
     InitializeComponent(); 
    } 

    private void ChangeBackgroundButton_OnClick(object sender, RoutedEventArgs e) 
    { 
     BackgroundColor = new SolidColorBrush(Colors.CornflowerBlue); 
    } 
} 

如果您網格背景屬性綁定到「BACKGROUNDCOLOR」。

<Window x:Class="ListBoxStackoverflow.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525" 
    x:Name="WindowsWithDependencyProperty"> 

<Grid Background="{Binding ElementName=WindowsWithDependencyProperty, Path=BackgroundColor}"> 
    <Button x:Name="ChangeBackgroundButton" 
      HorizontalAlignment="Left" VerticalAlignment="Top" 
      Click="ChangeBackgroundButton_OnClick">Change Background</Button> 
</Grid> 

請注意,這只是一個可能的解決方案。

1

我不知道,如果這個屬性可以是一個綁定一個,但通常它應該是。如果是這樣,您必須將控件的DataContext設置爲包含您的屬性的類的實例。

如果它在同一個控件/窗口/類中,那麼控件/窗口的構造函數或Loaded事件中的一個簡單的this.DataContext = this任何將爲您完成的工作。

1

該類需要實現INotifyPropertyChanged,並且該屬性需要在set方法中引發PropertyChanged事件才能使綁定正常工作。

還要確保您的對象的數據上下文設置爲後面的代碼。一種方法是在xaml窗口聲明中。設置這樣的數據上下文:

的DataContext = {綁定的RelativeSource = {RelativeSource.Self}}