gpt4 book ai didi

c# - 用字符串路径绑定(bind)背景

转载 作者:行者123 更新时间:2023-12-03 10:25:17 28 4
gpt4 key购买 nike

我尝试将 ViewModel 中的字符串(这是 png 的路径)绑定(bind)到网格背景。该字符串可以为空。它工作得很好,但在输出 cmd 是

System.Windows.Data Error: 23 : Cannot convert '' from type '' to type 'System.Windows.Media.ImageSource' for 'en-US' culture with default conversions; consider using Converter



如何将字符串路径绑定(bind)到后台以避免此错误?
我当前的绑定(bind):
现场控制.CS:
        public string BackgroundPath
{
get
{
return (string)GetValue(BackgroundPathProperty);
}
set
{
SetValue(BackgroundPathProperty, value);
}
}

public static readonly DependencyProperty BackgroundPathProperty =
DependencyProperty.Register("BackgroundPath", typeof(string), typeof(FieldControl), new PropertyMetadata(null));

字段控制.XAML:
        <Grid.Background>
<ImageBrush
ImageSource="{
Binding Path=BackgroundPath,
Mode=OneWay,
UpdateSourceTrigger=PropertyChanged,
RelativeSource={
RelativeSource Mode=FindAncestor,
AncestorType={x:Type UserControl}
}
}" />

</Grid.Background>

在 MainWindow.XAML 中:
        <ItemsControl
ItemsSource="{Binding FieldsVM}">

...

<ItemsControl.ItemTemplate>
<DataTemplate>
<controls:FieldControl
BackgroundPath="{Binding Path=BackgroundPath }"/>
</DataTemplate>
</ItemsControl.ItemTemplate>

</ItemsControl>

最佳答案

从编译器中删除错误的一种方法是创建一个 IValueConverter 并按照编译器的建议在 ImageBrush 元素中使用。

IValueConverter 可以这样写:

[ValueConversion(typeof(string), typeof(ImageSource))]
public class StringToImageSourceConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value == null) return null;

var path = value.ToString();
return new BitmapImage(new Uri(path, UriKind.RelativeOrAbsolute));
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotSupportedException();
}
}

在 FieldControl 的 xaml 中:
<UserControl.Resources>
<local:StringToImageSourceConverter x:Key="StringToImageSourceConverter" />
</UserControl.Resources>

<Grid Height="100">
<Grid.Background>
<ImageBrush ImageSource="{Binding Path=BackgroundPath, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, ElementName=Uc1,
Converter={StaticResource StringToImageSourceConverter}}" />
</Grid.Background>
</Grid>

在此之后,您不应该从编译器中看到错误。

我在 this 中测试代码项目。

关于c# - 用字符串路径绑定(bind)背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61507050/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com