我可以绑定一个WPF控件字段的属性?(Can I bind a WPF control to a f

2019-06-26 12:14发布

因为我需要分裂类之间的一些功能,我得出了以下的情况

XAML代码

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

视图模型

...
public MyInternalObject MyObjectField;
...

为MyObject类

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

它不工作,除非我在复制视图模型类的MyBoolean属性。

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

有没有人有一个想法?

Answer 1:

不,你不能。 由于绑定系统使用反射来找到

物业在DataContext的(即你的VM)

它不查找领域。 我希望这将有所帮助。



Answer 2:

你可以没有( 在WPF 4.5版可以绑定到一个静态的属性 )。 但是你可以创建在App.xaml.cs你的财产

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

和来自世界各地的绑定。

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


Answer 3:

相反的元素结合到一个领域的财产,我改变了元素的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和寻呼机(第一,上一个,下一个,最后一页)。 所述MainWindowView(包括数据网格)的元素被绑定到在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>


文章来源: Can I bind a WPF control to a field's property?