2014-09-10 48 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

相關問題