一、WPF绑定各种数据源索引
object数据源
Binding的基础可参考WPF 绑定基础
二、WPF绑定各种数据源之xml数据源,此时的XML源写在界面了,当然也可以独立成文件。
<Window.Resources>
<Con:BackgroundConverter x:Key=
"BackgroundConverter"
/>
<XmlDataProvider x:Key=
"myPerson3"
>
<x:XData>
<PersonF xmlns=
""
>
<person Name=
"Person1"
>
<ID>1</ID>
<Name>XiaoA</Name>
<Age>49</Age>
</person>
<person Name=
"Person2"
>
<ID>2</ID>
<Name>XiaoB</Name>
<Age>29</Age>
</person>
<person Name=
"Person3"
>
<ID>3</ID>
<Name>XiaoC</Name>
<Age>103</Age>
</person>
<person Name=
"Person4"
>
<ID>4</ID>
<Name>XiaoD</Name>
<Age>59</Age>
</person>
</PersonF>
</x:XData>
</XmlDataProvider>
</Window.Resources>
|
下面是绑定的代码。此时需要注意,原来用Path改成了XPath,因为这是XML源,并且ItemsSource 改成 ItemsSource="{Binding Source={StaticResource myPerson3},XPath=/PersonF/person}"
<ListView Height=
"262"
Margin=
"0,32,56,0"
ItemsSource=
"{Binding Source={StaticResource myPerson3},XPath=/PersonF/person}"
VerticalAlignment=
"Top"
Name=
"listView3"
HorizontalAlignment=
"Right"
Width=
"310"
>
<ListView.View>
<GridView>
<GridViewColumn Header=
"编号"
DisplayMemberBinding=
"{Binding XPath=ID}"
Width=
"100"
/>
<GridViewColumn Header=
"姓名"
DisplayMemberBinding=
"{Binding XPath=Name}"
Width=
"100"
/>
<GridViewColumn Header=
"年龄"
Width=
"100"
>
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Grid.Column=
"1"
Text=
"{Binding XPath=Age}"
Foreground=
"{Binding XPath=Age,Converter={StaticResource BackgroundConverter}}"
/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
|
下面是值转换
public
class
BackgroundConverter : IValueConverter
{
#region IValueConverter Members
object
Convert(
object
value,Type targetType,
object
parameter,System.Globalization.CultureInfo culture)
{
Color color =
new
Color();
int
num =
int
.Parse(value.ToString());
if
(num > 100)
color = Colors.Yellow;
else
if
(num < 50)
color = Colors.LightGreen;
else
color = Colors.LightPink;
return
new
SolidColorBrush(color);
}
object
ConvertBack(
throw
new
NotImplementedException();
}
#endregion
}
|
效果图:
2.使用外部XML数据源,只需做如下修改
<Window.Resources>
<XmlDataProvider x:Key=
"myPerson3"
Source=
"/Person.xml"
/>
</Window.Resources>
|
3.如果使用外部XML数据源,并且采用C#代码的形式,则如下:
XmlDocument doc =
new
XmlDocument();
XmlDataProvider provider =
new
XmlDataProvider();
provider.Document = doc;
provider.XPath =
@"/PersonF/person"
;
listView3.DataContext = provider;
listView3.SetBinding(ListView.ItemsSourceProperty,255)!important">new
Binding());
|
当然也可以使用XMLDataProvider的Source属性,此时只需做如下修改:
XmlDataProvider provider =
new
XmlDataProvider();
provider.Source =
new
Uri(
@"F:\\XMLFile1.xml"
);
provider.XPath =
@"/PersonF/person"
;
|
其他不变。
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/ 欢迎任何形式的转载,未经作者同意,请保留此段声明!