Can I bind a WPF control to a field's property?

前端 未结 3 1082
闹比i
闹比i 2020-12-11 18:43

Because I needed to split some functionality between classes, I\'ve arrived at the following situation

xaml code



        
相关标签:
3条回答
  • 2020-12-11 19:08

    No you cant . Because binding system uses Reflection to find the

    Property in DataContext(i.e your VM)

    It does not look for fields . I hope this will help.

    0 讨论(0)
  • 2020-12-11 19:26

    Instead of binding an element to a field's property I changed the DataContext of the element to the required field.

        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();
        }
    

    In this example I have a DataGrid and Pager (first, prev, next, last page) below it. The elements of the MainWindowView (including the DataGrid) are binded to properties in the MainWindowViewModel but the pager buttons are binded to the properties of 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>
    
    0 讨论(0)
  • 2020-12-11 19:30

    You can't yet (in WPF Version 4.5 you can bind to a static property). But you can create your property in App.xaml.cs

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

    and bind from everywhere.

    <CheckBox IsChecked="{Binding MyBoolean, Source={x:Static Application.Current}}">
    
    0 讨论(0)
提交回复
热议问题