【问题标题】:How to properly bind Checkbox property如何正确绑定 Checkbox 属性
【发布时间】:2019-01-07 14:51:32
【问题描述】:

我正在开发一个 wpf 应用程序,我现在正在处理复选框 当我像这样将 Ischecked 属性设置为“True”时的问题:

   <CheckBox  Visibility="{Binding checkVisibility}" IsChecked="true" 
   IsEnabled="True"></CheckBox>

我的复选框被选中 但是当我尝试绑定一个值为“true”的布尔属性时,我的复选框始终未选中 我看不到问题在哪里

这是我的 xaml

 <CheckBox  Visibility="{Binding checkVisibility}" IsChecked="{Binding Path=test,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" IsEnabled="True"></CheckBox>

这是我的财产

public bool _test = true;

public bool test {
    get {
        return _test;
    }
    set {
        if (_test == value) {
            return;
        }

        _test = value;
        RaisePropertyChanged("test");
    }
}

我希望我的复选框反映我的属性值,反之亦然,但事实并非如此,因为我的复选框始终未选中 我错过了什么?

编辑 这是我的虚拟机:

namespace X{
public class MyViewModel :  
{ 
public MyViewModel()
{
  TestCheckbox();
}
#Region Properties

    public bool _test1 = true;
    public bool test1
    {
        get
        {
            return _test1;
        }

        set
        {
            if (_test1 == value)
            {
                return;
            }

            _test1 = value;
            RaisePropertyChanged("test1");
        }
    }

 ObservableCollection<Output> _output_List;
    public ObservableCollection<Output> output_List
    {
        get { return _output_List; }
        set
        {
            if (_output_List == value) return;
            _output_List = value;
            RaisePropertyChanged("output_List");
        }

    }
#EndRegion
#Region ButtonCommand
  private RelayCommand _SetOutputPropertiesCommand;

    public RelayCommand SetOutputPropertiesCommand => _SetOutputPropertiesCommand
                ?? (_SetOutputPropertiesCommand = new RelayCommand(
                () =>
                {   
                        foreach (Output item in output_List)
                        {
                          item.myvalue=Test2;
                        }
                    }

                }));

#EndRegion
#Region Method
  public void TestCheckbox()
    {
     Console.Writeline(Test2);
    }
#EndRegion    

            }
  public class Output
{
    public string label { get; set; }
    public string type { get; set; }
    public bool myvalue { get; set; }
    public bool Test2 { get; set; }
    [System.ComponentModel.DataAnnotations.Schema.NotMapped]
    [JsonIgnore]
    public string checkVisibility { get; set; }
}
}

我的 Xaml:我的复选框集成在 DataGrid 视图中

                    <DataGrid x:Name ="GridO"  Style="{x:Null}"
                    ItemsSource= "{Binding output_List,UpdateSourceTrigger=PropertyChanged}"

                  AutoGenerateColumns="False" CellStyle="{StaticResource Body_Content_DataGrid_Centering}"
                  Margin="5,0" IsReadOnly="True" SelectionMode="Single" RowHeight="50" Height="Auto">


                        <DataGrid.Columns>

                            <DataGridTextColumn Width="40*" Binding="{Binding label}">
                                <DataGridTextColumn.HeaderTemplate>
                                    <DataTemplate>
                                        <TextBlock  Text="Input"></TextBlock>
                                    </DataTemplate>
                                </DataGridTextColumn.HeaderTemplate>
                            </DataGridTextColumn>

                            <DataGridTextColumn  Width="40*" Binding="{Binding type}">
                                <DataGridTextColumn.HeaderTemplate>
                                    <DataTemplate>
                                        <TextBlock  Text = "Type"></TextBlock>
                                    </DataTemplate>
                                </DataGridTextColumn.HeaderTemplate>
                            </DataGridTextColumn>


                            <DataGridTemplateColumn Width="20*" >
                                <DataGridTemplateColumn.Header>
                                    <TextBlock Text="Value" />
                                </DataGridTemplateColumn.Header>
                                <DataGridTemplateColumn.CellTemplate>
                                    <DataTemplate>
                                            <CheckBox Margin="20,0,0,0" Visibility="{Binding checkVisibility }" IsChecked="{Binding Test2,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" IsEnabled="True"></CheckBox>
                                    </DataTemplate>
                                </DataGridTemplateColumn.CellTemplate>
                            </DataGridTemplateColumn>

                        </DataGrid.Columns>
                    </DataGrid>
   <Button x:Name="Valid_output" Cursor="Hand" Background="Transparent"  Height="55"  Width="140" Margin="0,0,20,0" Command="{Binding SetOutputPropertiesCommand}"  >

绑定正在使用“Test2”,而不是使用与 Test2 不在同一类的“Test1” 注意: Button 命令(与“Test1”属于同一类)运行良好

我的 DataTemplate:在 App.xaml 中

  xmlns:v="clr-namespace:X.View"
  xmlns:vm="clr-namespace:X"
   <DataTemplate DataType="{x:Type vm:MyViewModel}">
            <v:MyWindow/>

【问题讨论】:

  • 你确定你的DataContext吗?绑定设置看起来是正确的,所以我假设您的复选框根本找不到要绑定的 test 属性。
  • 正确绑定。您的整体表单 DATACONTEXT 应该绑定到包含公开的 get/set "Test" 属性的类,然后它应该可以工作。
  • @DRapp 我的 DataContext 很好,因为我正在绑定界面中的其他元素(标签...)并且它正在工作,唯一的问题是 Checkbox
  • checkVisibility 属性是否与test 属于同一类?可见性绑定是否有效?
  • @Artholl 不,他们不在同一个班级检查可见性运行良好我将我的测试属性移到同一个班级并且它有效!

标签: c# wpf checkbox


【解决方案1】:

我在DataGrid 中看到了主要问题。您将ItemsSource 设置为一个集合,因此对于DataGrid 中的每一行,数据源都是该集合中的一项。不是你的MyViewModel

这就是Test2 工作的原因——它在类中,实例在集合中。

您可以尝试在没有 DataGrid 的情况下将 CheckBox 添加到窗口并绑定 Test1 - 它应该可以工作。

如果你真的想使用MyViewModel 中的某些属性,你可以,但这并不容易。你必须有类似的东西:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:YourNamespace"

<!--...something...-->

<DataGrid.Resources>
   <local:BindingProxy x:Key="Proxy" Data="{Binding}" />
</DataGrid.Resources>

<!--...something...-->

然后您在DataGrid 中的绑定将如下所示:

IsChecked="{Binding Data.Test1, Source={StaticResource Proxy}}"

当然,我不知道您的应用程序的确切设置,因此您必须根据它们完成/更改代码。

【讨论】:

  • 对于集合项目类型这是一个拼写错误我修复了它;因为这是一种机密,所以我必须小心
  • 明白,所以我删除了第一段。其余的应该仍然适合您。
  • 也谢谢你,我相信问题出在 DataGrid 资源上,一旦我得到问题,我会发布一个完整的答案,详细说明
【解决方案2】:

我建议你添加一个 ViewModelBase 类,像这样

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = 
    null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

使用此 ViewModelBase 类扩展您的 ViewModel 并实现您的属性

private bool myProperty;

public bool MyProperty { get; set; OnPropertyChanged(); }

那么你只需要绑定你的属性

<CheckBox IsChecked="{Binding MyProperty}"></CheckBox>

编辑:要将 ViewModel 设置为 View 的 DataContext,您可以从代码中设置它

MyView.DataContext = new MyViewModel();

或从视图中,在窗口/用户控件中

<Window x:Class="MyApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MyApplication"
    Title="MainWindow" Height="350" Width="525"
    DataContext="local.MyViewModel">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    • 2018-07-13
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    相关资源
    最近更新 更多