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>
同じことをコードビハインドで実装したいと思います。私は次のことをしました:
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);
VS出力で次のエラーが発生します
"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')"
ここでの助けは大歓迎です!