在 WPF 数据网格 MVVM 中创建一个倒数计时器列
Create a countdown timer column in WPF datagrid MVVM
我一直在使用 datagridview 并将其源绑定到 BindingList。我在更新数据网格的计时器列值时遇到问题。每次我更改计时器的值时,数据网格都不会更新。我已经尝试了很多解决方案,我想出了以下代码,但仍然没有用:
这是我的 XAML:
<DataGrid ItemsSource="{Binding MyList}">
<DataGridTextColumn Header="Timer" Binding="{Binding Path=Countdown, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataGrid>
这是我的 Class:
public class MyClass
{
public string Countdown {get;set;}
}
这是我的视图模型:
public class MyViewModel
{
private BindingList<MyClass> _myList;
public BindingList<MyClass> MyList
{
get { return _myList; }
set
{
_myList= value;
NotifyOfPropertyChange(() => MyList); //I am using Caliburn's Screen
}
}
}
下面是我如何更改 属性:
void OnButtonClick()
{
var fireAndForget = Task.Run(async () =>
{
int currentRowIndex = 0;
for (int i = 30; i > 0; i--)
{
MyList[currentRowIndex].CountDown = i.ToString();
MyList.ResetBindings();
await Task.Delay(1000);
}
}
}
这只会在计时器列中显示 30,并且不会更新。
我也试过使用 TrulyObservableCollection 和 FullyObservableCollection,都不好。我还尝试通过创建一个 localMyList 并执行 MyList = localMyList
但仍然没有更新
来更改整个 MyList
您忘记通知 属性 已更改。
也一样
public class MyClass
{
private string _countdown;
public string Countdown
{
get { return _countdown; }
set
{
_countdown = value;
NotifyOfPropertyChange(() => Countdown);
}
}
}
我一直在使用 datagridview 并将其源绑定到 BindingList。我在更新数据网格的计时器列值时遇到问题。每次我更改计时器的值时,数据网格都不会更新。我已经尝试了很多解决方案,我想出了以下代码,但仍然没有用:
这是我的 XAML:
<DataGrid ItemsSource="{Binding MyList}">
<DataGridTextColumn Header="Timer" Binding="{Binding Path=Countdown, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataGrid>
这是我的 Class:
public class MyClass
{
public string Countdown {get;set;}
}
这是我的视图模型:
public class MyViewModel
{
private BindingList<MyClass> _myList;
public BindingList<MyClass> MyList
{
get { return _myList; }
set
{
_myList= value;
NotifyOfPropertyChange(() => MyList); //I am using Caliburn's Screen
}
}
}
下面是我如何更改 属性:
void OnButtonClick()
{
var fireAndForget = Task.Run(async () =>
{
int currentRowIndex = 0;
for (int i = 30; i > 0; i--)
{
MyList[currentRowIndex].CountDown = i.ToString();
MyList.ResetBindings();
await Task.Delay(1000);
}
}
}
这只会在计时器列中显示 30,并且不会更新。
我也试过使用 TrulyObservableCollection 和 FullyObservableCollection,都不好。我还尝试通过创建一个 localMyList 并执行 MyList = localMyList
但仍然没有更新
您忘记通知 属性 已更改。
也一样public class MyClass
{
private string _countdown;
public string Countdown
{
get { return _countdown; }
set
{
_countdown = value;
NotifyOfPropertyChange(() => Countdown);
}
}
}