3

我有一个 Window ,ListBox它有一个DataTemplate, 绑定到一个ObservableCollectionof LogItems。的ItemsSourceListBox代码中设置到集合中;上的绑定TextBoxTextBlock组成的绑定DataTemplate在 XAML 中设置。到目前为止,如此传统。但是,我需要TextBlock在运行时设置字体大小/系列。目前,此信息保存在静态 cGlobals 类中。所以我需要能够将 绑定TextBlock.TextLogItems集合,但将TextBlock.FontSize属性绑定到cGlobals.LogFontSize属性。我该如何做到这一点,或者通过下面 XAML 中概述的绑定,或者在代码中?

       <ListBox   . . .  .  >

        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid  HorizontalAlignment="Stretch" . . .  . >

                    <Grid.RowDefinitions>
                        <RowDefinition  Height="20"  />
                        <RowDefinition Height="*" MinHeight="40" />
                    </Grid.RowDefinitions>

                    <TextBox Grid.Row="0"  Background="Honeydew" Text="{Binding  Mode=OneWay, Path=Header,  . . . . />
                    <TextBlock FontSize="{Binding ??????}"  Grid.Row="1" Text="{Binding  Path=BodyText}"  />

                </Grid>
            </DataTemplate >
        </ListBox.ItemTemplate >
    </ListBox>
4

2 回答 2

1

xml

<Window x:Class="WpfApplication6.StaticBinding"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApplication6"

    Title="StaticBinding" Height="300" Width="300">
<Grid>
    <TextBlock FontSize="{Binding Source={x:Static local:Global.FontSize}}" Text="abc"/>
</Grid>

全球的

public class Global
{ 
    public static double FontSize
    {
        get { return 20.0; }
    }
}
于 2013-08-08T00:38:53.073 回答
0

您将需要声明类型 cGlobals 的公共属性,但该类不能是静态的,因为您需要将其用作返回类型。您似乎没有遵循 Model-View-ViewModel 模式,因为您在代码隐藏而不是 XAML 中分配 ItemsSource,因此您需要在代码隐藏中声明该属性。在您的代码隐藏中(您的 .xaml.cs 文件)

private CGlobals _cGlobals;

public CGlobals CGlobals{get{return _cGlobals;}}

public CodeBehindConstructor(){
    _cGlobals = new CGlobal{FontSize = 12, FontFamily="Times New Roman"};

}



xaml:

<Window  Name="TheWindow">

 <TextBlock FontSize="{Binding CGlobals.FontSize, ElementName=TheWindow}"  Grid.Row="1" Text="{Binding  Path=BodyText}"  />


</Window>
于 2013-08-08T00:46:01.933 回答