用于在WinRT中使用MVVM Light Toolkit填充TextBox的Progressbar

时间:2015-06-11 15:02:56

标签: c# wpf xaml mvvm windows-runtime

我有一个包含少量TextBox元素和进度条的表单。我希望在TextBox分配了一些值时更新进度条。

因此,当一个值设置为TextBox时,如果长度不等于0,则增加ProgressPercent;

问题在于我不知道用什么条件来检查是否有任何值设置在之前,如果TextBox再次变为空白则会减少。

Bellow你有我的代码到目前为止

ViewModel

private string firstName { get; set; }
private string progressPercent { get; set; }

public string FirstName
{
    get
    {
        return this.firstName;
    }
    set
    {
        this.firstName = value;
        this.RaisePropertyChanged(() => this.FirstName);

        var vm1 = (new ViewModelLocator()).MainViewModel;
        if (value.Length != 0)              //   Checks the string length 
        {
            vm1.ProgressPercent += 3;
        }
    }
}
public int ProgressPercent
{
    get
    {
        return this.progressPercent;
    }
    set
    {
        this.progressPercent = value;
        this.RaisePropertyChanged(() => this.ProgressPercent);
    }
}

XAML

<StackPanel>
    <ProgressBar x:Name="progressBar1" 
                 Value="{Binding ProgressPercent ,Mode=TwoWay}"  
                 HorizontalAlignment="Left" 
                 IsIndeterminate="False" 
                 Maximum="100"
                 Width="800"/>
    <TextBlock Text="First Name"/>
    <TextBox x:Name="FirstNameTextBox" Text="{Binding FirstName, Mode=TwoWay}"/>
</StackPanel>

任何想法如何做到这一点?

2 个答案:

答案 0 :(得分:2)

跟这样的布尔跟踪:

 private bool firstNamePoints=false;
 public string FirstName
 {
    get
    {
        return this.firstName;
    }
    set
    {
        this.firstName = value;
        this.RaisePropertyChanged(() => this.FirstName);

        var vm1 = (new ViewModelLocator()).MainViewModel;
        if (value.Length != 0)              //   Checks the string length 
        {
          if(!firstNamePoints)
           {
            vm1.ProgressPercent += 3;
            firstNamePoints=true;
           }
        }
        else
        {
          if(firstNamePoints)
          {
            vm1.ProgressPercent -= 3;
            firstNamePoints=false;
          }
         }
    }
}

答案 1 :(得分:2)

如果财产没有改变,您不应该通知财产变更。你总能确定它何时变空,反之亦然。

    public string FirstName
    {
        get
        {
            return this.firstName;
        }
        set
        {
            if (this.firstName != value)
            {
                bool oldValueIsEmpty = String.IsNullOrWhiteSpace(this.firstName);
                this.firstName = value;
                this.RaisePropertyChanged(() => this.FirstName);

                var vm1 = (new ViewModelLocator()).MainViewModel;
                if (String.IsNullOrWhiteSpace(value))              //   Checks the string length 
                {
                    vm1.ProgressPercent -= 3;
                }
                else if (oldValueIsEmpty)
                {
                    vm1.ProgressPercent += 3;
                }
            }
        }
    }