1

I've something like this in the xaml.

 <Image.Style>
            <Style TargetType="Image">
                <Setter Property="Source" Value="../Images/FolderImage.png" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=img, Path=IsEnabled}" 
                                                                           value="False">
                        <Setter Property="Source" Value="../Images/FolderImage_Disabled.png" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Image.Style>

and I want to implement the same thing in code behind. I've done the following:

 Style imgStyle = new Style();

        imgStyle.TargetType = typeof(Image);

        Setter imgSetter = new Setter();
        imgSetter.Property = Image.SourceProperty;
        imgSetter.Value = bmpImg;
        imgStyle.Setters.Add(imgSetter);

        disabledImage = new BitmapImage();
        disabledImage.BeginInit();
        disabledImage.UriSource = new Uri("pack://application:,,,/../Images/FolderImage_Disabled.png");
        disabledImage.EndInit();

        DataTrigger trg = new DataTrigger();
        Binding trgBinding = new Binding();
        trgBinding.ElementName = "img";
        trgBinding.Path = new PropertyPath("IsEnabled");
        trg.Value = false;
        trg.Binding = trgBinding;
        imgStyle.Triggers.Add(trg);

        imgSetter = new Setter();
        imgSetter.Property = Image.SourceProperty;
        imgSetter.Value = disabledImage;
        trg.Setters.Add(imgSetter);
        menuIcon.SetValue(Image.StyleProperty, imgStyle);

I get the following error in the VS output

"System.Windows.Data Error: 4 : Cannot find source for binding with 
    reference 'ElementName=img'. BindingExpression:Path=IsEnabled; DataItem=null;
    target element is 'Image' (Name='img'); target property is 'NoTarget' (type 'Object')"

Any help here will be appreciated!

1 Answer 1

2

I'm not sure why you'd want to do it like that.. but, try setting the binding source.

tryBinding.Source = this;

Here is another way you might want to consider.

  • create a boolean property in the code behind
  • bind that property to the IsEnabled property of the img - twoway mode
  • in the setter of the property, change the source of the image depending on the value.
Sign up to request clarification or add additional context in comments.

1 Comment

I had to move the xaml part to code behind to reduce the load time. And you are right...due to lack of time, I was blindly following the xaml. Thanks for showing the right way :) Appreciate it :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.