2012-02-01 29 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

相关问题