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!
I’m not sure why you’d want to do it like that.. but, try setting the binding source.
Here is another way you might want to consider.