双向绑定无法正常工作?

时间:2017-07-14 05:09:08

标签: wpf xaml

我的页面背后有代码

  public event PropertyChangedEventHandler PropertyChanged;
    public bool Executing
    {
        get
        {
            return _executing;
        }
        set
        {
            _executing = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                    new PropertyChangedEventArgs("Executing"));
            }

        }
    }

    public endpoints()
    {
        InitializeComponent();
        this.Executing = false;
        DataContext = this;

    }

   private void Button_Click(object sender, RoutedEventArgs e)
    {
         Executing=true;
        var accessPoints = wifi.GetAccessPoints();
         Executing=false;

        lvAccessPoints.ItemsSource = accessPoints.Select(ap => new WifiAccess
        {
            Executing=true;
            Points = ap,
            Password = string.Empty,
        }).ToList();


    }

和我的xaml

 <ProgressBar x:Name="progress" Grid.Row="2" Grid.ColumnSpan="3" Minimum="0" Maximum="100" IsIndeterminate="True" Visibility="Collapsed"></ProgressBar>
<MultiDataTrigger>
                            <MultiDataTrigger.Conditions>
                                <Condition Binding="{Binding Path=Executing,  UpdateSourceTrigger=PropertyChanged}" Value="True" />
                            </MultiDataTrigger.Conditions>
                            <Setter TargetName="progress" Property="Visibility" Value="Visible" />
                        </MultiDataTrigger>

在顶部我有

<Page.Resources>
    <BooleanToVisibilityConverter x:Key="boolToVis" />
</Page.Resources>

但我期待进度条在开始时隐藏,并且在执行时应该显示为真。但它一直在显示。

我保留了一个像这样的文本框

<TextBlock Grid.Column="1" Text="{Binding Executing,UpdateSourceTrigger=PropertyChanged}" FontWeight="Bold" Foreground="White" Padding="10,0" FontSize="15" VerticalAlignment="Center"/>

总是显示错误,不会改变

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

UI未更新,因为在执行Button Click处理程序期间UI线程被阻止。

你可以让它像这样异步工作:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    Executing = true;

    var accessPoints = await Task.Run(() => wifi.GetAccessPoints());

    Executing = false;
    ...
}

为了使您执行属性设置器线程安全,您应该像下面所示编写它,其中PropertyChanged事件只被访问一次。

public bool Executing
{
    get { return _executing; }
    set
    {
        _executing = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Executing)));
    }
}

在Executing Binding上设置UpdateSourceTrigger=PropertyChanged也没有意义,因为这样做没有任何效果。似乎也不需要MultiDataTrigger。所以你可以使用这样一个简单的DataTrigger:

<DataTrigger Binding="{Binding Executing}" Value="True" />