tof*_*tim 14 c# data-binding wpf multithreading ivalueconverter
我有一个很慢的WPF转换器(计算,在线提取等).如何异步转换以便我的UI不会冻结?我发现这一点,但解决的办法是将转换器代码在属性- http://social.msdn.microsoft.com/Forums/pl-PL/wpf/thread/50d288a2-eadc-4ed6-a9d3-6e249036cb71 -这我宁愿不这样做.
以下是演示该问题的示例.这里的下拉列表将冻结,直到睡眠过去.
namespace testAsync
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Windows;
using System.Windows.Data;
using System.Windows.Threading;
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyNumbers = new Dictionary<string, int> { { "Uno", 1 }, { "Dos", 2 }, { "Tres", 3 } };
this.DataContext = this;
}
public Dictionary<string, int> MyNumbers
{
get { return (Dictionary<string, int>)GetValue(MyNumbersProperty); }
set { SetValue(MyNumbersProperty, value); }
}
public static readonly DependencyProperty MyNumbersProperty =
DependencyProperty.Register("MyNumbers", typeof(Dictionary<string, int>), typeof(MainWindow), new UIPropertyMetadata(null));
public string MyNumber
{
get { return (string)GetValue(MyNumberProperty); }
set { SetValue(MyNumberProperty, value); }
}
public static readonly DependencyProperty MyNumberProperty = DependencyProperty.Register(
"MyNumber", typeof(string), typeof(MainWindow), new UIPropertyMetadata("Uno"));
}
public class AsyncConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
object result = null;
if (values[0] is string && values[1] is IDictionary<string, int>)
{
DoAsync(
() =>
{
Thread.Sleep(2000); // Simulate long task
var number = (string)(values[0]);
var numbers = (IDictionary<string, int>)(values[1]);
result = numbers[number];
result = result.ToString();
});
}
return result;
}
private void DoAsync(Action action)
{
var frame = new DispatcherFrame();
new Thread((ThreadStart)(() =>
{
action();
frame.Continue = false;
})).Start();
Dispatcher.PushFrame(frame);
}
public object[] ConvertBack(object value, Type[] targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
Run Code Online (Sandbox Code Playgroud)
和XAML:
<Window x:Class="testAsync.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:testAsync"
Title="MainWindow" Height="200" Width="200">
<Window.Resources>
<local:AsyncConverter x:Key="asyncConverter"/>
</Window.Resources>
<DockPanel>
<ComboBox DockPanel.Dock="Top" SelectedItem="{Binding MyNumber, IsAsync=True}"
ItemsSource="{Binding MyNumbers.Keys, IsAsync=True}"/>
<TextBlock DataContext="{Binding IsAsync=True}"
FontSize="50" FontWeight="Bold" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource asyncConverter}">
<Binding Path="MyNumber" IsAsync="True"/>
<Binding Path="MyNumbers" IsAsync="True"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DockPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)
请注意,所有绑定现在都是IsAsync ="True",但这没有用.

组合框将卡住2000毫秒.
我知道你说你不想从属性设置器调用翻译,但是我认为它比IValueConverter/ 更干净IMultiValueConverter.
最终,您希望从组合框中设置所选数字的值,并立即从中返回.您希望推迟更新显示/翻译的值,直到翻译过程完成.
我认为对数据进行建模更加清晰,这样翻译后的值本身就是一个只能由异步进程更新的属性.
<ComboBox SelectedItem="{Binding SelectedNumber, Mode=OneWayToSource}"
ItemsSource="{Binding MyNumbers.Keys}"/>
<TextBlock Text="{Binding MyNumberValue}" />
Run Code Online (Sandbox Code Playgroud)
public partial class MainWindow : Window, INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
MyNumbers = new Dictionary<string, int> { { "Uno", 1 }, { "Dos", 2 }, { "Tres", 3 } };
DataContext = this;
}
public IDictionary<string, int> MyNumbers { get; set; }
string _selectedNumber;
public string SelectedNumber
{
get { return _selectedNumber; }
set
{
_selectedNumber = value;
Notify("SelectedNumber");
UpdateMyNumberValue();
}
}
int _myNumberValue;
public int MyNumberValue
{
get { return _myNumberValue; }
set
{
_myNumberValue = value;
Notify("MyNumberValue");
}
}
void UpdateMyNumberValue()
{
var key = SelectedNumber;
if (key == null || !MyNumbers.ContainsKey(key)) return;
new Thread(() =>
{
Thread.Sleep(3000);
MyNumberValue = MyNumbers[key];
}).Start();
}
public event PropertyChangedEventHandler PropertyChanged;
void Notify(string property)
{
var handler = PropertyChanged;
if(handler != null) handler(this, new PropertyChangedEventArgs(property));
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用a DispatcherFrame,这是一个示例转换器:
public class AsyncConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
object result = null;
DoAsync(() =>
{
Thread.Sleep(2000); // Simulate long task
result = (int)value * 2; // Some sample conversion
});
return result;
}
private void DoAsync(Action action)
{
var frame = new DispatcherFrame();
new Thread((ThreadStart)(() =>
{
action();
frame.Continue = false;
})).Start();
Dispatcher.PushFrame(frame);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
Run Code Online (Sandbox Code Playgroud)
我建议看看BackgroundWorker. 它可以在后台线程上执行转换,然后在 UI 线程上引发完成事件。
请参阅http://www.dotnetperls.com/backgroundworker
| 归档时间: |
|
| 查看次数: |
4043 次 |
| 最近记录: |