2012-02-01 42 views
0

我創建了一個列表框,我可以根據該列表框動態添加和刪除項目UI相應的更改,並且工作正常。在列表框中更改項目屬性時遇到的問題

<ListBox Name="MsgsList" ItemsSource="{Binding Items}" Style="{StaticResource MsgsBoxStyle}"> 
    <ListBox.ItemTemplate> 
     <DataTemplate x:Name="MsgsDataTemplate"> 
      <StackPanel Tag="{Binding MsgTagInfo}" ManipulationCompleted="StackPanel_Msgs_ManipulationCompleted"> 

       <toolkit:GestureService.GestureListener> 
        <toolkit:GestureListener Hold="GestureListener_Hold" Tap="GestureListener_Tap"/> 
       </toolkit:GestureService.GestureListener> 

       <Grid x:Name="ContentPanelInner" Grid.Row="1" Width="500"> 
        <StackPanel x:Name="stackPanelInner" Width="500"> 

         <Grid VerticalAlignment="Top" Width="500"> 
          <Grid.ColumnDefinitions> 
           <ColumnDefinition /> 
           <ColumnDefinition /> 
          </Grid.ColumnDefinitions> 

          <TextBlock Grid.Column="0" Text="{Binding MsgTitle}" Style="{StaticResource MsgLine1}" /> 
          <TextBlock Grid.Column="1" Text="{Binding MsgDate}" Style="{StaticResource MsgDate}" /> 
         </Grid> 
         <TextBlock Text="{Binding MsgBody}" Style="{StaticResource MsgLine2}" /> 
        </StackPanel> 
       </Grid> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

,但我不知道如何改變風格爲特定項目的文本塊,亦即基於某些情況下,如果我想改變特定項目的文本框(S)的顏色不知道如何訪問。

有人可以幫我這個嗎?謝謝。

回答

1

我如果你只是想改變的項目風格方面,例如它的顏色,你可能暴露,作爲模型對象的屬性,您具有約束力。例如,添加屬性TextColor並將其綁定如下:

<TextBlock Text="{Binding MsgBody}" Style="{StaticResource MsgLine2}"> 
    <TextBlock.Color> 
    <SolidColorBrush Color="{Binding TextColor}"/> 
    </TextBlock.Color> 
</TextBlock> 

這將優先於通過樣式定義的顏色。

+1

這就是我將如何做一個非常簡單的例子,但我傾向於使用轉換器來處理任何不平凡的事情,因爲它有助於從視圖中分離模型。 – ZombieSheep 2012-02-01 14:48:10

+0

謝謝你的簡單回答。 – rplusg 2012-02-02 10:07:57

2

大概沒有做到這一點最簡單的方法,但可以說從關注點分離的觀點是通過使用一個轉換器,並結合最乾淨的,爲了要監視的財產......

例如,如果你的模型基於一個名爲myProperty的布爾屬性改變狀態,你可以使用類似這樣的東西。

<StackPanel Background={Binding myProperty, Converter={StaticResource myBindingConverter}" /> 

您的轉換器應根據您的財產的價值返回一個SolidColorBrush。

public class AlternateRowColour : IValueConverter 
{ 
    SolidColorBrush normal = new SolidColorBrush(Colors.Transparent); 
    SolidColorBrush highlighted = new SolidColorBrush(Color.FromArgb(255, 241, 241, 241)); 

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     var myValue = (bool)value 
     return myValue ? highlighted : normal ; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotImplementedException(); 
    } 
+0

對不起,我不明白。我怎樣才能用這種方法來改變一個特定的項目,你能詳細說明一下嗎? – rplusg 2012-02-01 14:49:01

+0

如果您的支持模型具有一個名爲myProperty的布爾屬性,則轉換器將返回不同的畫筆,具體取決於值是true還是false。除了在模型中設置標誌之外,您不應該手動執行任何工作來檢查值。 – ZombieSheep 2012-02-01 14:51:37

+0

感謝您的輸入,但作爲一個懶惰的開發者,我想採取科林的答案,但給了你一個贊成票。 – rplusg 2012-02-02 09:59:11

相關問題