我可以将WPF控件绑定到字段的属性吗?

时间:2012-07-24 16:23:26

标签: c# wpf binding wpf-controls

因为我需要在类之间拆分某些功能,所以我遇到了以下情况

xaml代码

<CheckBox IsChecked="{Binding MyObjectField.MyBoolean}"  />

查看模型

...
public MyInternalObject MyObjectField;
...

MyObject类

public class MyInternalObject {
    ...
    public bool MyBoolean { get; set; }
    ...
}

除非我在View Model类中复制MyBoolean属性,否则它不起作用。

public bool MyBoolean 
{ 
    get { return MyInternalObject.MyBoolean; }
    set { MyInternalObject.MyBoolean=value; }
}

有没有人有想法?

3 个答案:

答案 0 :(得分:5)

你还不能(in WPF Version 4.5 you can bind to a static property)。但您可以在App.xaml.cs中创建属性

public partial class App : Application
{
    public bool MyBoolean { get; set; }
}

并从任何地方绑定。

<CheckBox IsChecked="{Binding MyBoolean, Source={x:Static Application.Current}}">

答案 1 :(得分:4)

不,你不能。因为绑定系统使用Reflection来查找

  

DataContext中的属性(即您的VM)

它不寻找字段。我希望这会有所帮助。

答案 2 :(得分:0)

我没有将元素绑定到字段的属性,而是将元素的DataContext更改为必需的字段。

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        MainWindowView mainWindowView = new MainWindowView();
        var mainWindowViewModel = new MainWindowViewModel();
        mainWindowView.DataContext = mainWindowViewModel;
        mainWindowView.pagerView.DataContext = mainWindowViewModel.pager;
        mainWindowView.Show();
    }

在这个例子中,我有一个DataGrid和Pager(第一页,上一页,下一页,最后一页)。 MainWindowView的元素(包括DataGrid)绑定到MainWindowViewModel中的属性,但是寻呼机按钮绑定到mainWindowViewModel.pager的属性。

MainWindowView:

    <DataGrid Name="dgSimple" ItemsSource="{Binding DisplayedUsers}" MaxWidth="200" Grid.Row="0" SelectedItem="{Binding SelectedRow}"></DataGrid>
    <view:PagerView x:Name="pagerView" Grid.Row="2"/>

PagerView:

<UserControl x:Class="wpf_scroll.View.PagerView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:wpf_scroll.View"
         mc:Ignorable="d" 
         d:DesignHeight="30" d:DesignWidth="350">
<StackPanel Orientation="Horizontal" Grid.Row="1">
    <Label Content="Page size:"/>
    <TextBox Text="{Binding PageSize}" Width="30" VerticalContentAlignment="Center"
                 HorizontalContentAlignment="Center"></TextBox>
    <Button Content="First" Command="{Binding FirstPageCommand}"></Button>