0

我正在尝试制作一个进度条,当属性值更改时更新我已经关注了其他问题,但我不知道它有什么问题。

这是 XAML 代码:

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1" x:Class="WpfApplication1.MainWindow"
        Title="MainWindow">
    <Grid Margin="0,0,-8,1">
        <ProgressBar Value="{Binding Progreso, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}}}" Margin="105,95,207,350"/>
        <Button Content="Button" Click="Button_Click" Margin="218,232,333,217"/>

    </Grid>
</Window>

它基本上是一个带有绑定的进度条和一个带有监听器的按钮,它将 Progreso 增加 10 这是 C# 代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void NotifyPropertyChanged(string sProp)
    {

        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(sProp));
        }
    }

    float progreso = 10;
    public float Progreso
    {
        get
        {
            return progreso;
        }
        set
        {
            progreso = value;
            NotifyPropertyChanged("Progreso");
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        this.Progreso = this.Progreso + 10;
    }

}

我试图保持简单,但我无法让它工作,对此的任何帮助将不胜感激。

编辑:我也尝试过 UpdateSourceTrigger=PropertyChanged 但这也没有用

4

2 回答 2

2

AncestorType 似乎不工作的财产。所以你有两个选择:

  1. 设置窗口并Name查找DataContextElementName
  2. 设置DataContextthis代码后面并删除 RelativeSource 部分
于 2013-11-02T21:42:17.860 回答
2

您的问题是您错过了INotifyPropertyChanged这样的接口实现声明:

public partial class MainWindow : Window, INotifyPropertyChanged {
  //....
}

注意:使用RelativeSource工作正常,我对此进行了测试。尽管使用DataContext是一种方便且推荐的方式,但使用只是一种隐式设置方式。Source

更新

关于使用DataContext

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

<ProgressBar Value="{Binding Progreso}" Margin="105,95,207,350"/>
于 2013-11-02T21:56:00.093 回答