我在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')"
任何帮助都将不胜感激!
答案 0 :(得分:2)
我不确定你为什么要那样做..但是,尝试设置绑定源。
tryBinding.Source = this;
这是您可能想要考虑的另一种方式。