2014-12-03 39 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}}