强制ListView在UWP中刷新或无效

时间:2017-02-18 07:10:56

标签: c# uwp

我有ListView ItemTemplate。我想将ItemTemplate中的一个控件背景绑定到2个属性,其中一个属性位于ItemsSource中,另一个属性位于我的页面中。由于UWP没有multibinding支持,我将它绑定到ItemSource中的一个属性,而对于我页面中的另一个属性,我想在我的代码后面处理它。

<ListView >
<ListView.ItemTemplate>
          <DataTemplate>
                   <Border HorizontalAlignment="Stretch"
                           x:Name="myborder"
                           Padding="5,0,5,0"
                           Background="{Binding myProperty, Converter={StaticResource convertPropertyToBgColor },ConverterParameter=border}">
                                <StackPanel Padding="0,10,10,10"
                                            Background="{Binding myProperty, Converter={StaticResource convertPropertyToBgColor},ConverterParameter=stack}">
                                       <TextBlock Text="{Binding Text}">
                                </StackPanel>
                  </Border>
            </DataTemplate>
</ListView.ItemTemplate>
</ListView>

convertPropertyToBgColor我从资源中获取画笔。

并且在我的第二个所需属性更改后的代码中我更改了我的资源。所以我从资源中使用的画笔得到了改变,因此我想再次调用该转换器来刷新背景,我调用了updateLayout,但它没有刷新我的ListView,也没有再次调用myConvereter。如何强制ListView重新创建或刷新它所创建的项目?

1 个答案:

答案 0 :(得分:0)

通常,您的类应该实现INotifyPropertyChanged,然后在更改属性后,通常在其 setter 中,您还会调用 OnPropertyChanged 事件,这将更新您的UI。有很多例子,here is one

另一种方式,可能是调用Bindings.Update(),但通常你可能应该使用上面的方法。

让我的评论更清晰 - 这样的事情是可能的:

<StackPanel Orientation="Horizontal" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView x:Name="myList" Width="200">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Border HorizontalAlignment="Stretch"
                       x:Name="myborder"
                       Padding="5,0,5,0"
                       Background="{Binding Path=DataContext.MyProperty, ElementName=myList}">
                    <StackPanel Padding="0,10,10,10">
                        <TextBlock Text="{Binding}"/>
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListView.ItemTemplate>
        <x:String>Element 1</x:String>
        <x:String>Element 2</x:String>
        <x:String>Element 3</x:String>
    </ListView>
    <Button Content="Change" Click="Button_Click"/>
</StackPanel>
代码背后的代码:

public sealed partial class MainPage : Page, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    void RaiseProperty(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

    private SolidColorBrush myPropety = new SolidColorBrush(Colors.Red);
    public SolidColorBrush MyProperty
    {
        get { return myPropety; }
        set { myPropety = value; RaiseProperty(nameof(MyProperty)); }
    }

    public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }
    private void Button_Click(object sender, RoutedEventArgs e) => MyProperty = new SolidColorBrush(Colors.Blue);
}