繁体   English   中英

网格内的Silverlight,TextBlock

[英]Silverlight, TextBlock inside Grid

我是Silverlight的新手,并且给了我一个修改任务。 我的问题很简单(如果在asp.net Webforms中完成)。 基本上,在网格中,我想将年份附加到这样的内容上。

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

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

等..等等

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>

我只想让这一年充满活力,因此它每年都会变化。 请帮忙。

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

最好使用绑定来完成。 在Silverlight中, 大多数数据源绑定到代码隐藏的属性(即ViewModel)。

简而言之:

  1. 将页面的DataContext设置为代码隐藏类(通常为ViewModel)
  2. ViewModel必须实现INotifyPropertyChanged接口
  3. 绑定TextBox的文本以在ViewModel中使用Date属性进行代码计算

一旦设置了DataContext,就可以编写XAML,如下所示:

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

您的ViewModel属性将如下所示:

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" ) );
            }
         }
     }
  ...
}

这可能对您有帮助。 仅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" 

您也可以显示其他DateTime属性:Now.Day,Today.Month等。

我重新阅读了您的问题,我认为您需要做这样的事情。 由于您在网格中工作,因此可以命名您的文本块。

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

在您的背后代码中,在文本块内放置文本应该足够了。

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

我希望这能解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM