ITPub博客

首页 > > > wpf 难以理解的Binding 的问题 求解释大侠

wpf 难以理解的Binding 的问题 求解释大侠

作者:llittle 时间:2019-09-12 11:05:50 0 删除 编辑
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        Title="MainWindow" Height="350" Width="525" Name="UI">

    <Window.Resources>
        <CollectionViewSource x:Key="Items" Source="{Binding ElementName=UI, Path=Items}" >
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="Id" />
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </Window.Resources>

    <Grid>
        <ListBox ItemsSource="{Binding Source={StaticResource Items}}" />
    </Grid>
</Window>

后台代码:

public partial class MainWindow : Window
    {
        private ObservableCollection<MyObject> myVar = new ObservableCollection<MyObject>();

        public MainWindow()
        {
            InitializeComponent();

            Items.Add(new MyObject { Description = "Stack", Id = 5 });
            Items.Add(new MyObject { Description = "OverFlow", Id = 1 });
            Items.Add(new MyObject { Description = "StackOverFlow", Id = 2 });
            Items.Add(new MyObject { Description = "Stack", Id = 1 });
            Items.Add(new MyObject { Description = "Stack", Id = 0 });
            Items.Add(new MyObject { Description = "OverFlow", Id = 7 });
        }

        public ObservableCollection<MyObject> Items
        {
            get { return myVar; }
            set { myVar = value; }
        }
    }

    public class MyObject
    {
        public int Id { get; set; }
        public string Description { get; set; }

        public override string ToString()
        {
            return string.Format("Desc: {0}, Id: {1}", Description, Id);
        }
    }


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/813/viewspace-3126838/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-12

  • 博文量
    448
  • 访问量
    4362