WPF绑定功能非常方便,有时候点击某值时在另t一处显示此值的另一表现形式或调用其对应的其它值,用WPF值转换功能会很方便,下面就一LISTBOX和TEXTBLOCK控件,把LISTBOX中的值转换成除以1000后的结果显示在TextBlock中

1、值转换类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data; namespace WpfApplication4
{
class MyValueConvert:IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
int v = int.Parse(value.ToString());
return v / + "M";
}
catch (Exception ex)
{
return Binding.DoNothing;
}
} public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
}

2、主窗口C#

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes; namespace WpfApplication4
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private ObservableCollection<string> obj = new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent(); obj.Add("");
obj.Add("");
obj.Add("");
obj.Add("");
obj.Add("");
this.listbox.ItemsSource = obj;
}
}
}

3、显示界面

<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
Title="MainWindow" Height="" Width="">
<Window.Resources>
<local:MyValueConvert x:Key="myCvt"></local:MyValueConvert>
</Window.Resources>
<Grid>
<StackPanel>
<TextBlock Name="tb" Margin="" Text="{Binding ElementName=listbox,Path=SelectedItem,Converter={StaticResource myCvt}}"></TextBlock>
<ListBox Name="listbox"/>
</StackPanel>
</Grid>
</Window>
05-11 13:47