从task中的object设置属性值

时间:2013-09-19 08:29:29

标签: c# wpf mvvm

我有一个名为Settings的对象。 它有一个名为BusyDoingAction的属性bool

public class Settings : ObservableObject
    {
        private bool busyDoingAction;
        public bool BusyDoingAction 
        {
            get { return this.busyDoingAction; }
            set
            {
                this.busyDoingAction= value;
                OnPropertyChanged(() => BusyDoingAction);
            }
        }

我有另一个名为FileAdding的类,

private readonly string[] files;
private bool busy;
public FileAdding(string[] files, bool busyAction)
        {
            this.files = files;
            this.busy= busyAction;
        }

现在,在我的ViewModel中,我有以下内容:

var fileAdding = new FileAdding(files, Settings.BusyDoingAction);            

            if (!fileAdding.Initialize())
                return;

            Task<bool>.Factory.StartNew(() =>
            {
                fileAdding.Execute(CToken);
                return fileAdding.Deinitialize();
            }, CToken);
        }

在FileAdding Initialize()函数中我有:

public bool Initialize()
        {
           busy  = true;
           return true;
        }

public bool Deinitialize()
         {
           busy  = false;
           return true;
         }

问题是: BusAdDoingAction在FileAdding中没有变化,并且我没有获得该属性的任何值更改通知。

该属性绑定到我的应用程序中的mainGrid,并使用它来检测应用程序是否繁忙并根据BusyDoingAction的值启用/禁用网格

我不知道我做错了什么,但我需要在busyDoingAction.Intialize / Deinitialize函数中设置BusyDoingAction的属性值。

任何帮助都非常感谢..

2 个答案:

答案 0 :(得分:1)

FileAdding类应该这样..你应该有Settings属性...并在UI上绑定到Settings.BusyDoingAction

    private readonly string[] files;
    private Settings setting;
    public FileAdding(string[] files, Settings setting)
            {
                this.files = files;
                this.setting= setting;
            }

public Settings Settings
        {
            get { return this.setting; }
            set
            {
                this.setting= value;
                OnPropertyChanged(() => Settings);
            }
        }

public bool Initialize()
        {
           Settings.BusyDoingAction = true;
           return true;
        }

public bool Deinitialize()
         {
           Settings.BusyDoingAction = false;
           return true;
         }

答案 1 :(得分:1)

这样做的:

var fileAdding = new FileAdding(files, Settings.BusyDoingAction);

您只是将当前值或Settings.BusyDoingAction复制到FileAction.busy

Settings.BusyDoingActionFileAdding.busy

之间没有关联

要解决您的问题,一种方法是将Settings引用传递给FileAdding

private readonly string[] files;
private readonly Settings settings;
public FileAdding(string[] files, Settings settings)
{
    this.files = files;
    this.settings = settings;
}

然后在:

public bool Initialize()
{
   this.settings.BusyDoingAction = true;
   return true;
}

public bool Deinitialize()
{
   this.settings.BusyDoingAction = false;
   return true;
}