微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

WPF绑定语法问题

如何解决WPF绑定语法问题

| 下面的代码应该显示一个包含三个列表框的堆栈,每个列表框包含所有系统字体的列表。第一个未排序,第二个和第三个按字母顺序排列。但是第三个是空的。调试时,在“ VS输出”窗口中没有看到任何绑定错误消息。 标记是:
<Window x:Class=\"FontList.MainWindow\"
    xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"
    xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"
    xmlns:local=\"clr-namespace:FontList\"
    Title=\"MainWindow\" Height=\"600\" Width=\"400\">
<Grid>
    <Grid.RowDeFinitions>
        <RowDeFinition Height=\"*\"></RowDeFinition>
        <RowDeFinition Height=\"*\"></RowDeFinition>
        <RowDeFinition Height=\"*\"></RowDeFinition>
    </Grid.RowDeFinitions>
    <ListBox Grid.Row=\"0\" ItemsSource=\"{Binding Source={x:Static Fonts.SystemFontFamilies}}\" />
    <ListBox Grid.Row=\"1\" ItemsSource=\"{Binding Path=SystemFonts}\" />
    <ListBox Grid.Row=\"2\" ItemsSource=\"{Binding Source={x:Static local:MainWindow.SystemFonts}}\" />
</Grid>
后面的代码是:
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace FontList
{
    public partial class MainWindow : Window
    {
        public static List<FontFamily> SystemFonts { get; set; }

        public MainWindow() {
            InitializeComponent();
            DataContext = this;
            SystemFonts = Fonts.SystemFontFamilies.OrderBy(f => f.ToString()).ToList();
        }
    }
}
第三个绑定有什么问题?     

解决方法

        您需要先初始化ѭ2need,然后再调用
InitalizeComponent
。 WPF绑定无法知道属性的值已更改。
public MainWindow() {
    SystemFonts = Fonts.SystemFontFamilies.OrderBy(f => f.ToString()).ToList();
    InitializeComponent();
    DataContext = this;
}
或更妙的是,使用:
static MainWindow() {
    SystemFonts = Fonts.SystemFontFamilies.OrderBy(f => f.ToString()).ToList();
}

public MainWindow() {
    InitializeComponent();
    DataContext = this;
}
    ,        绑定是在
InitializeComponent
期间创建的,而
SystemFonts
null
的创建。设置后,绑定无法知道该属性的值已更改。 您还可以在静态构造函数中设置“ 2”,这可能是更可取的选择,因为它是静态属性。否则,每次
MainWindow
的实例都将更改静态属性。
public partial class MainWindow : Window {
    public static List<FontFamily> SystemFonts{get; set;}

    static MainWindow {
       SystemFonts = Fonts.SystemFontFamilies.OrderBy(f => f.ToString()).ToList();
    }

    ...
}
    

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。