将文本值绑定到WPF中的Datagrid [英] Binding a text value to Datagrid in WPF
本文介绍了将文本值绑定到WPF中的Datagrid的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里我将一个值绑定到datagrid,如下所示:
Here i am binding a value to the datagrid as show given below
<DataGrid Grid.Row="1" Name="dgDept" IsReadOnly="True" AutoGenerateColumns="False" BorderBrush="Black" BorderThickness="1 1 1 1" Margin="10,15,10,0" MouseDoubleClick="OndgDeptMouseDoubleClick" IsEnabled="True" PreviewKeyDown="dgDept_KeyDown" >
<DataGrid.Columns>
<DataGridTextColumn Header="Status" Width="*" Binding="{Binding Status}"/>
</DataGrid.Columns>
</DataGrid>
var data=dbobj.GetDataFromDB("Select Status from tblDept");
dgDept.ItemsSource=data;
状态有0,1,2,3值。现在我的问题是怎样才能我将文本绑定为一,二,三,四,数据网格而不是0,1,2,3
任何想法实现这一目标?
Status has 0,1,2,3 values.Now my problem is how can i bind text as one,two three,four to datagrid instead of 0,1,2,3
Any idea to achieve this?
推荐答案
您好,
您可以使用IValueConverter,如下所示。我在这里粘贴了一个例子看看。
IValueConverter转换器参考XAML
Hi,
you can use IValueConverter as below. I have pasted here a example have a look.
IValueConverter convertor Reference in XAML
xmlns:convertor="clr-namespace:ApplicationShell"
添加窗口资源
Add Window Resource
<Window.Resources>
<convertor:InttoString x:Key="inttoString"/>
</Window.Resources>
我的XAML
My XAML
<datagrid x:name="studentDG" height="150" autogeneratecolumns="False" xmlns:x="#unknown">
<datagrid.columns>
<datagridtextcolumn binding="{Binding IDs, Converter={StaticResource inttoString}}" header="ID" />
</datagrid.columns>
</datagrid>
我的代码背后
My Code behind
List<teststu> IDs = new List<teststu>();
IDs.Add(new TestStu { IDs = 1 });
IDs.Add(new TestStu { IDs = 2 });
IDs.Add(new TestStu { IDs = 3 });
IDs.Add(new TestStu { IDs = 4 });
studentDG.ItemsSource = IDs;
和我的IValueConverter
and my IValueConverter
public class InttoString : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
switch (value + "")
{
case "1":
return "One";
case "2":
return "Two";
case "3":
return "Three";
case "4":
return "Four";
default:
return "Zero";
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
如果您无法理解,请告诉我。
let me know if you can't understand.
>
这篇关于将文本值绑定到WPF中的Datagrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文