【问题标题】:Rebinding Image source while using a converter?使用转换器时重新绑定图像源?
【发布时间】:2011-03-09 16:10:41
【问题描述】:

我有一个按钮,里面有一张图片。该按钮多次出现在数据网格上,用于显示行的状态。当用户单击按钮时,它会将行上的基础对象的状态更改为启用或禁用。这是按钮的外观:

<data:DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <Button CommandParameter="{Binding}" HorizontalAlignment="Center">
            <Image Source="{Binding Converter={StaticResource EnableDisableConverter}}" Height="25" Width="25" />
        </Button>
   </DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>

转换器根据状态正确返回正确的图像。问题是我已经切换到 MVVM 模型,而我用于更改图像的代码将不再起作用。我以前的样子是这样的:

Image img = (Image)btn.Content;
if (c.Status == Administration.Web.ObjectStatus.Enabled) {
    img.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/enable-icon.png", UriKind.Relative));
} else {
    img.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri("/Images/disable-icon.png", UriKind.Relative));
}

在更改状态的命令期间,我尝试对包含对象的属性进行更改,但它并未反映在 UI 上。如果我对屏幕进行硬刷新,则状态会正确更改。有没有办法在当前情况下重新绑定图像?

【问题讨论】:

    标签: silverlight mvvm binding


    【解决方案1】:

    将图像的源绑定到某个 bool Enabled 属性,然后您的 EnableDisableConverter 可以在每次更改后对该值做出反应。

    XAML:

    <data:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button CommandParameter="{Binding}" HorizontalAlignment="Center">
                <Image Source="{Binding IsEnabled, Converter={StaticResource EnableDisableConverter}}" Height="25" Width="25" />
            </Button>
       </DataTemplate>
    </data:DataGridTemplateColumn.CellTemplate>
    

    视图模型:

    ...
    public bool IsEnabled 
    {
        get
        {
            return _isEnabled;
        }
        set
        {
            _isEnabled=value;
            NotifyPropertyChanged("IsEnabled");
        }
    }
    ...
    

    转换器:

    public object Convert(object value, ...)
    {
        if((bool)value)
            return uri of image1;
        else
            return uri of image2;
    
    }
    

    但我不知道网格中的对象是什么,ViewModel 是什么。可能有问题。关键是要将 IsEnabled 属性正确绑定到网格中的那些对象。

    【讨论】:

    • 最终绑定到对象上的状态字段并且效果很好。谢谢!
    猜你喜欢
    • 2011-06-13
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多