WPF绑定,其中value = X.

gul*_*aek 3 .net c# wpf xaml

嗨,只想知道它是否可以在xaml中绑定到列表,其中值具有一定值.防爆.在下面的例子中,Xaml是否只能显示项目,其中Price = 20?

我问,因为我要绑定一个包含另一个列表的对象列表,我只想显示某个项目,具体取决于值.因此,我试图避免使用C#解决方案.

MainWindow.xaml

   <Window x:Class="Binding_Test.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListView ItemsSource="{Binding}"/>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

MainWindow.xaml.cs

public MainWindow()
        {
            DataContext = BuildList();
            InitializeComponent();
        }

        List<Product> BuildList()
        {
            var list = new List<Product>();
            var y = 1;
            for (var i = 0; i < 100; i++)
            {
                list.Add(new Product{Name = string.Format("Item {0}",i), Price = y++ * 10 });
                if (y > 3)
                    y = 1;
            }
            return list;
        }
Run Code Online (Sandbox Code Playgroud)

Product.cs

public class Product
    {
       public string Name { get; set; }
       public int Price { get; set; }

       public override string ToString()
       {
           return string.Format("{0} \t{1}", Name, Price.ToString("C2"));
       }
}
Run Code Online (Sandbox Code Playgroud)

Leo*_*rke 7

使用带有适当过滤器的CollectionViewSource.在这种情况下,xaml看起来像这样:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>
    <CollectionViewSource Source="{Binding}" x:Key="filtered" Filter="CollectionViewSource_Filter" />
</Window.Resources>
<Grid>
    <ListView ItemsSource="{Binding Source={StaticResource filtered}}"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

过滤器事件看起来像这样:

private void CollectionViewSource_Filter(object sender, FilterEventArgs e)
        {
            if ((e.Item as Product).Price == 20)
            {
                e.Accepted = true;
            }
            else
            {
                e.Accepted = false;
            }
        }
Run Code Online (Sandbox Code Playgroud)