我有一个很慢的 WPF 转换器(计算、在线获取等)。我怎样才能异步转换,这样我的 UI 就不会卡住?我找到了这个,但解决方案是将转换器代码放在属性中 - http://social.msdn.microsoft.com/Forums/pl-PL/wpf/thread/50d288a2-eadc-4ed6-a9d3-6e249036cb71 - 我宁愿不这样做。
下面是一个演示问题的示例。此处下拉菜单将卡住,直到 Sleep 结束。
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();
}
}
和 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>
请注意,所有绑定(bind)现在都是 IsAsync="True",但这没有帮助。
组合框将卡住 2000 毫秒。
最佳答案
我知道您说过您不想从属性 setter 调用转换,但我认为这是一种比 IValueConverter
/IMultiValueConverter
更简洁的方法。
最后,您想要设置组合框中所选数字的值,并立即返回。您想推迟更新显示/翻译的值,直到翻译过程完成。
我认为对数据建模会更清楚,这样转换后的值本身就是一个属性,该属性仅由异步过程更新。
<ComboBox SelectedItem="{Binding SelectedNumber, Mode=OneWayToSource}"
ItemsSource="{Binding MyNumbers.Keys}"/>
<TextBlock Text="{Binding MyNumberValue}" />
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));
}
}
关于c# - 如何在单独的线程上运行 Converter 内的代码,以便 UI 不卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6542572/