Click here to Skip to main content
15,885,998 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Binding the Duration property of DoubleAnimation inside Storyboard doesn't update converter, when UpdateTarget() is called manually.

MainWindow.xaml:
XML
<Grid>
    <local:UserControl2/>
</Grid>


UserControl2.xaml:
XML
<UserControl.Resources>
    <local:Converter x:Key="Converter"></local:Converter>
    <Storyboard x:Key="Storyboard">
        <DoubleAnimation
            Duration="{Binding ElementName=ellipse, Path=Width, Converter={StaticResource Converter}, Mode=OneTime}">
        </DoubleAnimation>
    </Storyboard>
</UserControl.Resources>
<Grid x:Name="grid" Background="Red" MouseDown="Grid_MouseDown">
    <Ellipse x:Name="ellipse"></Ellipse>
</Grid>


UserControl2.xaml.cs:
C#
public partial class UserControl2 : UserControl
{
    public UserControl2()
    {
        InitializeComponent();
    }

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        storyboard = this.Resources["Storyboard"] as Storyboard;
        doubleAnimation = storyboard.Children[0] as DoubleAnimation;

        NameScope.SetNameScope(storyboard, NameScope.GetNameScope(this));
        NameScope.SetNameScope(doubleAnimation, NameScope.GetNameScope(this));

        BindingOperations.SetBinding(doubleAnimation, DoubleAnimation.DurationProperty,
            new Binding("Width") { Converter = new Converter(), ElementName = "ellipse" });
    }

    private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
    {
        BindingOperations.GetBindingExpression(doubleAnimation, DoubleAnimation.DurationProperty).UpdateTarget();
    }

    Storyboard storyboard;
    DoubleAnimation doubleAnimation;
}


Converter.cs:
C#
class Converter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        MessageBox.Show("Hello World!");
        return new System.Windows.Duration(TimeSpan.FromSeconds(1));
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}


What I have tried:

I tried the code I gave inside the description of the question, but the message "Hello World!" doesn't show, when I click on Grid on Window.
Posted
Updated 2-Aug-16 9:29am
v2
Comments
Kenneth Haugland 2-Aug-16 20:57pm    
Your problem is that the binding expression is null;
var bd = BindingOperations.GetBindingExpression(doubleAnimation, DoubleAnimation.DurationProperty);
If (bd != null) //do something
Ziya1995 3-Aug-16 2:56am    
I want to know why ElementName binding doesn't work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900