Search code examples
c#xmlwpfpropertygrid

How can I hide the property of PropertyGid in XML?


below is my XML generated by using XMLSerializer and there are propertygrid's properties. What I wish to do is to edit the contents in XML file so that the property can be hidden, instead of change the code using [browsable(false)]. For example, there are Name, ID, Mode and email, these 4 properties, and I want to hide then Name by editing the content in XML file. What should I do to achieve this?

<?xml version="1.0" encoding="utf-8" ?>
<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name xsi:type="xsd:string">Hello</Name>
  <ID xsi:type="xsd:string">1132701760</ID>
  <Mode xsi:type="xsd:string">burst</Mode>
  <Email xsi:type="xsd:string">[email protected]</Email>
</Person>


Solution

  • MVVM approach:

    Basically it implements by built-in class in .Net BooleanToVisibilityConverter:

    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="booleanVisibilityConverter"/>
    </UserControl.Resources>
    

    Let me show work example:

    XAML:

    <UserControl.Resources>
        <BooleanToVisibilityConverter x:Key="booleanVisibilityConverter"/>
    </UserControl.Resources>
    ...
    <Button Content="Hello, I am the button" Visibility="{Binding ShowButton, 
                    Converter={StaticResource booleanVisibilityConverter}}"/>
    

    ViewModel:

    private bool _showButton = false;
    public bool ShowButton
    {
       get { 
             //you can write logic here to get values from XML
             return _showButton; 
       }
       set
       {
          if (value != _showButton)
          {
             //you can write logic here to get values from XML
             _showButton = value;
             OnPropertyChanged("ShowButton");
          }
       }
    }
    

    If you want to change the Visibility of your Button in code, you can make it by this code in ViewModel:

    ShowButton = false;
    

    If you use code-behind approach:

    XAML:

    <Button Content="Hello, I am the button" Name="btn"/>
    

    Code-behind:

     //read xml file
     if(...your logic here...)
        btn.Visibitity= System.Windows.Visibility.Visible;