2014-09-10 96 views
0

我有一个带Gridview的xaml页面,它有一个Button.I使用分组的Item页面。这些按钮是基于返回的数据集生成的。 10个记录将显示10个按钮。Windows 8 metro应用程序:动态设计按钮样式。 C#和Xaml

 <GridView.ItemTemplate> 
         <DataTemplate> 
          <Grid HorizontalAlignment="Left" Width="Auto" Height="Auto" >      
           <Button Click="ItemView_ItemClick"> 
             <StackPanel Margin="5" > 
             <TextBlock Tag="cntCustName" Style="{ThemeResource CntNormalTextBlockStyle}" Text="{Binding CUSTOMERNAME }"/> 
             <TextBlock Tag="cntCatCode" Style="{ThemeResource CntLrgTextBlockStyle}" Text="{Binding CATEGORYCODE}"/> 
             <TextBlock Tag="cntDay" Style="{ThemeResource CntNormalTextBlockStyle}" Text="{Binding DAY}"/>        
            </StackPanel> 
           </Button> 
          </Grid> 
         </DataTemplate> 
        </GridView.ItemTemplate> 

我在foreach循环中获取数据。我希望能够根据我拥有的某些标准动态分配按钮 的样式。

 foreach (ContactData ContactData in _openContatcs) 
        { 
         if (ContactData.CFLAG) 
         { 
          //this is an example 
          Application.Current.Resources["contactSquare"] = ampStyle; 
         } 
         group.Items.Add(ContactData); 
        } 


     Styles are defined like this in a folder: Assests/Resources/BaseAPStyles.xaml 

     <Style x:Name="contactSquare" TargetType="Button"> 
       <Setter Property="BorderBrush" Value="Transparent"/> 
       <Setter Property="BorderThickness" Value="0"/> 
       <Setter Property="Height" Value="160"/> 
       <Setter Property="HorizontalAlignment" Value="Left"/> 
       <Setter Property="Margin" Value="5"/> 
       <Setter Property="VerticalAlignment" Value="Top"/> 
       <Setter Property="Width" Value="160"/> 
       <Setter Property="Template"> 
        <Setter.Value> 
         <ControlTemplate TargetType="Button"> 
          <Grid Background="#ffffc600"> 
           <ContentPresenter> 
           </ContentPresenter> 
          </Grid> 
         </ControlTemplate> 
        </Setter.Value> 
       </Setter> 
      </Style> 

我的按钮没有显示样式。我怎样才能做到这一点?

回答

0

使用x:key="contactSqaure"来查找应用程序资源中的样式。

然后,访问您想要设置样式的按钮并将样式指定给按钮。

yourButton.Style = Application.Resources.Current["contactSqaure"] as Style; 

您还可以在C#中定义样式,或编辑按钮的依赖项属性。

yourButton.Height = 160; 
yourButton.VerticalAlignment = VerticalAlignment.Center; 

加载时,您可以访问数据模板中的按钮。

<DataTemplate> 
    <Button Loaded="Button_Loaded" .../> 
.... 

void Button_Loaded(object sender, RoutedEventArgs args) 
{ 
    (sender as Button).Style = yourStyle; 
} 
+0

谢谢。问题是我无法直接访问按钮。我认为这是因为它在GridView的DataTemplate中。我无法获得按钮的属性。有任何想法吗? – user2320476 2014-09-10 14:20:22

+0

你想要做什么?每个Gridview项目都有不同的按钮样式?如果是这样,什么决定使用哪种风格?你有没有看过使用数据模板选择器? – 2014-09-10 15:03:26

相关问题