1
我在xaml中有類似的東西。如何通過觸發器從後面的代碼設置圖像源wpf
<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')"
任何幫助,這裏將不勝感激!
我不得不將xaml部件移到代碼後面以減少加載時間。你是對的......由於時間不夠,我盲目地追蹤着xaml。感謝您展示正確的方式:)欣賞它:) – Alerter