2011-03-09 53 views
1

我有一個按鈕,裏面有圖像。此按鈕多次顯示在數據網格上以顯示行的狀態。當用戶單擊該按鈕時,它將該行上的基礎對象的狀態更改爲啓用或禁用。這裏是按鈕的樣子:在使用轉換器時重新綁定圖像源?

<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。如果我對屏幕進行了硬刷新,則狀態會正確更改。目前情況下有沒有辦法重新塑造圖像?

回答

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; 

} 

但我不知道是什麼物體在網格中,什麼是視圖模型。可能有問題。重點是將IsEnabled屬性正確綁定到網格中的這些對象。

+0

結束綁定到對象上的狀態字段,並完美的工作。謝謝! – Josh 2011-03-10 15:35:54