【问题标题】:Binding image source to property not working将图像源绑定到属性不起作用
【发布时间】:2014-06-18 09:36:48
【问题描述】:

我在这个视图模型中有其他绑定工作正常。我不知道为什么这个不是。我尝试了多种不同的方法来使用绑定更新图像源。都失败了。这是我见过的最常见的方式,也是我在 Windows Phone 上完成的方式。我不确定为什么这在 WPF 中不起作用。

XAML

<ComboBox 
  ItemsSource="{Binding Keywords}" 
  SelectedItem="{Binding SelectedKeyword, Mode=TwoWay}">
  <ComboBox.ItemTemplate>
      <DataTemplate>
           <Label Width="280" Content="{Binding KeywordName}"/>   
      </DataTemplate>
  </ComboBox.ItemTemplate>
</ComboBox>

<Grid>
 <Image Source="{Binding LinkedImage}"/>
</Grid>

视图模型

public KeywordObject SelectedKeyword
{
    get { return _SelectedKeyword; }
    set { _SelectedKeyword = value; OnPropertyChanged("LinkedImage"); }
}

public Boolean _IsLinked
{
    get { return _SelectedKeyword.KeywordNumber.Length > 0; }
}

public ImageSource LinkedImage
{
    get 
    { 
        return _IsLinked ?

        new BitmapImage(new Uri("/images/checked.png", UriKind.RelativeOrAbsolute)) 
        :  
        new BitmapImage(new Uri("/images/unchecked.png", UriKind.RelativeOrAbsolute)); 
    }
}

public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged(string prop)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(prop));
    }
}

这是调试器中输出的异常

A first chance exception of type 'System.IO.IOException' occurred in PresentationFramework.dll
A first chance exception of type 'System.IO.IOException' occurred in PresentationCore.dll

【问题讨论】:

  • 放一个空集
  • 尝试从您的 uri 路径中删除前导 /
  • 检查this question。第一次机会异常不一定是代码中的错误。您可以将调试器设置为仅在未处理的异常上中断,这将消失。 Also this.

标签: c# wpf


【解决方案1】:

答案最终是路径需要pack://application:,,,/Specific.Project.Name;component

这是回答它的 SO 文章的链接

Image shows up in Visual Studio designer but not during run-time

这是最终结果的样子

<image Source="pack://application:,,,/Specific.Project.Name;component/images/checked.png"/>

我也能够将其注入绑定中,并且效果很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-18
    • 2012-04-03
    • 2019-12-14
    • 1970-01-01
    • 2012-06-24
    • 2015-01-04
    • 1970-01-01
    相关资源
    最近更新 更多