使用转换器时重新绑定图像源?

时间:2011-03-09 16:10:42

标签: silverlight mvvm binding

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

<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上反映它。如果我对屏幕进行硬刷新,则状态会正确更改。有没有办法在当前情况下重新绑定图像?

1 个答案:

答案 0 :(得分:2)

将图像的源绑定到某个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属性与网格中的那些对象进行核心绑定。

相关问题