wpf数据绑定常见问题

1.如何与当前页面的元素(如需要获取一个窗体的属性,那么本元素则需要向上寻找)

示例:绑定窗体Height属性,显示为300

<Window x:Class=”WpfApplication.Window5″    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”    xmlns:src=”clr-namespace:WpfApplication”    Title=”Window5″ Height=”300″ Width=”300″>    <Grid>        <Button Content=”{Binding Path=Height,RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type src:Window5}}}” Height=”23″ Margin=”114,0,90,64″ Name=”button1″ VerticalAlignment=”Bottom”></Button>    </Grid></Window>
 

2.绑定的数据类型转换参数问题(使用资源文件解决)

 

(1)ConverterParameter不是依赖属性,无法绑定,所以定义一个有依赖属性的元素作为资源文件(错误做法)

<Window x:Class=”WpfApplication.Window5″    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”    xmlns:src=”clr-namespace:WpfApplication”    Title=”Window5″ Height=”300″ Width=”300″>    <Grid>        <Grid.Resources>            <src:Demo x:Key=”aaa”></src:Demo>                        <Button x:Key=”abc” Content=”{Binding Path=Height,                RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type src:Window5}}}" />                    </Grid.Resources>        <Button Content=”{Binding Path=Height,            Converter={StaticResource aaa},ConverterParameter={StaticResource abc},            RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type src:Window5}}}" Height=”23″ Margin=”114,0,90,64″ Name=”button1″ VerticalAlignment=”Bottom”></Button>    </Grid></Window>
发现(1)的做法不正确 abc资源文件如果用了绑定语法的话,无法获取绑定的值,需要在代码中得到资源文件然后更改资源文件的属性
(2)在后端更改资源文件(正确做法)

Button aaa = this.Resources["abc"] as Button;aaa.Content = “xxxx”;
3.绑定到字典(注意没有字符串)

{Binding dd[xxx]}

 

4.设置DisplayMemberPath显示路径值(与重写ToString方法相同)

 

5.绑定选择对象

(1)先设置SelectedValuePath

(2)绑定SelectedItem

(3)绑定SelectedValue

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值