C# 从资源字典设置图像源
我有一个wpf应用程序,其中有一个tabcontrol,我从外部资源字典设置了它的ItemTemplate,在该模板中,我有一个图像控件,我将其绑定到ViewModel中的字符串属性“ImagePath”,并使用转换器将“ImagePath”转换为新的bitmapImage。我在外部资源Distinary中创建了转换器类实例。我在App.xaml中合并了外部字典 这是我的外部资源字典:C# 从资源字典设置图像源,c#,wpf,mvvm,C#,Wpf,Mvvm,我有一个wpf应用程序,其中有一个tabcontrol,我从外部资源字典设置了它的ItemTemplate,在该模板中,我有一个图像控件,我将其绑定到ViewModel中的字符串属性“ImagePath”,并使用转换器将“ImagePath”转换为新的bitmapImage。我在外部资源Distinary中创建了转换器类实例。我在App.xaml中合并了外部字典 这是我的外部资源字典: <ResourceDictionary xmlns="http://schemas.microsoft.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:helpers="clr-namespace:RH_Maize.Helper">
<helpers:ImageSourceConverter x:Key="ImageSourceConverter" />
<DataTemplate x:Key="ClosableTabItemTemplate">
<StackPanel Width="155"
Orientation="Horizontal"
Height="35">
<Image Height="25"
Width="30"
Source="{Binding Path=ImagePath,Converter={ StaticResource ImageSourceConverter}}"/>
<TextBlock TextWrapping="Wrap" Text="{Binding DisplayName}"
Width="100" Height="27" VerticalAlignment="Bottom" FontSize="15" Margin="3,0,0,0"/>
<Button Command="{Binding CloseCommand}"
Content="x" />
</StackPanel>
</DataTemplate>
我的ViewModel属性是:
private string _ImagePath;
public string ImagePath
{
get
{
return _ImagePath;
}
set
{
_ImagePath = value;
RaisePropertyChanged(() => ImagePath);
}
}
我的问题是converter classes convert方法根本没有调用。我的代码有什么问题?您根本不需要该转换器,因为WPF内置了从
string
和Uri
到ImageSource
的类型转换。删除它,然后检查是否调用了ImagePath
属性getter。当绑定不起作用时,需要调试这种情况。Visual Studio中的“输出”窗口中是否有错误?您是否在ImageSourceConverter.Convert
方法中设置了断点(在if
语句之外)?@Sheridan,如何调试绑定值首先,我会按照刚才的建议执行。然后,如果您仍然有问题,您可以遵循WPF Tutorial.NET网站上文章中的建议。
private string _ImagePath;
public string ImagePath
{
get
{
return _ImagePath;
}
set
{
_ImagePath = value;
RaisePropertyChanged(() => ImagePath);
}
}