将不同属性绑定到不同的源

时间:2013-08-07 23:41:32

标签: wpf binding

我有一个ListBox的窗口,其中DataTemplate绑定到ObservableCollection LogItemsItemsSource的{​​{1}}在集合的代码中设置;组成ListBox的{​​{1}}和TextBox上的绑定在XAML中设置。到目前为止,如此传统。但是,我需要在运行时为TextBlock设置字体大小/系列。目前,此信息保存在静态cGlobals类中。所以我需要能够将DataTemplate绑定到TextBlock集合,但TextBlock.Text属性绑定到LogItems属性。我怎么能这样做,或者通过下面的XAML中勾画出来的绑定,或者代码?

TextBlock.FontSize

2 个答案:

答案 0 :(得分:1)

XAML

<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; }
    }
}

答案 1 :(得分:0)

您需要声明Type cGlobals的公共属性,但该类不能是静态的,因为您需要将其用作返回类型。它看起来不像你在遵循Model-View-ViewModel模式,因为你在代码隐藏而不是XAML中分配ItemsSource,所以你需要在代码隐藏中声明属性。在你的Code-Behind(你的.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>