2012-10-11 36 views
1

我對Silverlight完全陌生,我被賦予了修改它的任務。我的問題很簡單(如果在asp.net webforms中完成)。 基本上,在網格中,我想附加一年這樣的事情。Silverlight,網格內的TextBlock

Jan + "-" + DateTime.Now.Year.ToString() 

Feb + "-" + DateTime.Now.Year.ToString() 

etc..etc ..

的XAML看起來像這樣

<Grid x:Name="ContentGrid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0"> 
       <Grid.Resources> 

<DataTemplate x:Key="mykey1"> 
         <Grid >....</Grid> 
</DataTemplate> 
<DataTemplate x:Key="mykey2"> 
         <Grid >....</Grid> 
</DataTemplate> 
<DataTemplate x:Key="mykey3"> 
         <Grid > 
<StackPanel Orientation="Vertical"> 
<Border BorderBrush="{StaticResource LogicaPebbleBlackBrush}" BorderThickness="1"> 
<StackPanel Orientation="Vertical"> 
<StackPanel Orientation="Horizontal" Style="{StaticResource HeaderStackPanel}"> 


<TextBlock Style="{StaticResource HeaderTextBlock}" Text="Jan-2013" Width="75" TextAlignment="Center"/> 
<TextBlock Style="{StaticResource HeaderTextBlock}" Text="Feb-2013" Width="75" TextAlignment="Center"/> 


</StackPanel> 
</StackPanel> 
</Grid> 
</DataTemplate> 
</ Grid> 
</DataTemplate> 

我只是想當年動態的,所以它每年的變化。請幫忙。

+0

你不能給你的TextBlocks一個ID並在代碼隱藏中設置它們的'.Text'屬性嗎? –

+0

我試過但我無法在後面的代碼中訪問它們。 – doms

回答

0

我不知道這是否可以直接在XAML中完成。

這最好使用綁定完成。在Silverlight中,您將綁定了大多數數據源到代碼隱藏中的屬性(即ViewModel)。

一言以蔽之:

  1. 設置頁面的DataContext的代碼隱藏類(通常是視圖模型)
  2. 視圖模型必須實現INotifyPropertyChanged接口
  3. 綁定你的文本框使用日期的文本在做代碼計算視圖模型屬性

一旦你有你的DataContext的設置,你可以寫XAML如下:

<TextBlock Text="{Binding Path=Year, Mode=OneWay}" /> 

您的視圖模型屬性將如下所示:

public class ViewModel : INotifyPropertyChanged 
{ 
    private DateTime _year = DateTime.Now; 
    public DateTime Year 
    { 
     get { return _year; } // <--- append whatever here or in the setter 
     set 
     { 
      _year = value; 

      if(this.PropertyChanged != null) 
      { 
       this.PropertyChanged(this, new PropertyChangedEventArgs("Year")); 
      } 
     } 
    } 
    ... 
} 
0

這可能會幫助你。這是唯一的XAML:

<Grid.Resources> 
     <System:DateTime x:Key="DateTimeDataSource"/> 
</Grid.Resources> 

<TextBlock DataContext="{Binding Source={StaticResource DateTimeDataSource}}" 
     Text="{Binding Today.Year}"> 
</TextBlock> 

請確保您添加這個命名空間:

xmlns:System="clr-namespace:System;assembly=mscorlib" 

你也能顯示日期時間等屬性:Now.Day,Today.Month等

+0

我有錯誤。 System.Windows.Markup.XamlParseException:未知元素:DateTime。 [Line:29 Position:66] Line 29指向 doms

+0

您是否已將此項添加到您的名稱空間中,並且您是否已在項目中引用它?xmlns:System =「clr namespace:System; assembly = mscorlib」 –

0

我重讀你的問題,我認爲你需要做這樣的事情。 由於您正在網格中工作,因此可以命名您的文本塊。

<TextBlock Style="{StaticResource HeaderTextBlock}" x:Name="JanTB" Width="75" TextAlignment="Center"/> 

在你的後面的代碼中,它應該足以將文本放置在文本塊內。

JanTB.Text = "Jan-" + Datetime.now.Year.ToString(); 

我希望這可以解決您的問題。