首页 > 代码库 > WPF值转换实例
WPF值转换实例
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 / 1000 + "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("1000"); obj.Add("10000"); obj.Add("100000"); obj.Add("10000000"); obj.Add("100000000"); 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="350" Width="525"> <Window.Resources> <local:MyValueConvert x:Key="myCvt"></local:MyValueConvert> </Window.Resources> <Grid> <StackPanel> <TextBlock Name="tb" Margin="20" Text="{Binding ElementName=listbox,Path=SelectedItem,Converter={StaticResource myCvt}}"></TextBlock> <ListBox Name="listbox"/> </StackPanel> </Grid></Window>
WPF值转换实例
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。