使用MVVM(无代码隐藏),我想在选择时隐藏DataGrid列,我有以下代码:

<DataGrid ItemsSource="{Binding SSID}" Grid.Row="1"  Margin="10,10,0,0" Height="200" Width="500" Grid.ColumnSpan="2" Name="dg" HorizontalAlignment="Left" AutoGenerateColumns="False">
    <DataGrid.Columns>
      <DataGridTextColumn Header="Network ID" Binding="{Binding _networkID}"></DataGridTextColumn>
      <DataGridTextColumn Header="SSID" Binding="{Binding _ssid}"></DataGridTextColumn>
      <DataGridTextColumn Header="VLAN" Binding="{Binding _vlan}"></DataGridTextColumn>
      <DataGridTextColumn Visibility="{Binding _authenticationMode}" Binding="{Binding _authenticationMode}"></DataGridTextColumn>
      <DataGridTextColumn Visibility="{Binding _authentication}" Binding="{Binding _authentication}"></DataGridTextColumn>
      <DataGridTextColumn Visibility="{Binding _staticWEPKeyType}" Binding="{Binding _staticWEPKeyType}"></DataGridTextColumn>
      <DataGridTextColumn Visibility="{Binding _staticWEPKeyLength}" Binding="{Binding _staticWEPKeyLength}"></DataGridTextColumn>
      <DataGridTextColumn Visibility="{Binding _staticWEPKey1}" Binding="{Binding _staticWEPKey1}"></DataGridTextColumn>
      <DataGridTextColumn Visibility="{Binding _staticWEPKey2}" Binding="{Binding _staticWEPKey2}"></DataGridTextColumn>
      <DataGridTextColumn Visibility="{Binding _staticWEPKey3}" Binding="{Binding _staticWEPKey3}"></DataGridTextColumn>
      <DataGridTextColumn Visibility="{Binding _staticWEPKey4}" Binding="{Binding _staticWEPKey4}"></DataGridTextColumn>
      <DataGridTextColumn Visibility="{Binding _wpaPersonalKeyAC}" Binding="{Binding _wpaPersonalKeyAC}"></DataGridTextColumn>
   </DataGrid.Columns>
</DataGrid>

C#代码是:
var ssid = new SSIDPropertyClass();

ssid._networkID = SSID.Count + 1;
ssid._ssid = EnteredSSIDAC;
ssid._vlan = VlanSSID;

if (ACSelectedSecurityType=="Static WEP")
{
    ssid._authenticationMode = ACSelectedSecurityType;
    ssid._authentication = ACStaticWEPSelectedAuthentication;

    ssid._staticWEPKeyType = ACStaticWEPSelectedKeyType;
    ssid._staticWEPKeyLength = ACStaticWEPSelectedKeyLength;

    ssid._staticWEPKey1 = StaticWEPKey1;
    ssid._staticWEPKey2 = StaticWEPKey2;
    ssid._staticWEPKey3 = StaticWEPKey3;
    ssid._staticWEPKey4 = StaticWEPKey4;

    SSID.Add(ssid);
}
else if(ACSelectedSecurityType=="WPA/WPA2 Personal")
{
    ssid._authenticationMode = ACSelectedSecurityType;
    ssid._wpaPersonalKeyAC = WpaACKey;

    SSID.Add(ssid);
}

我想要的是,如果执行块,那么它只会在datagrid中添加该块列,而对于其他if块则添加相同的情况。实际上,它总是显示多余的列,例如,当执行else if时,我只想显示我在SSID集合中添加的那两个,但它也会显示是否也阻塞了列。因此,简而言之,我想使多余的列可见为false。有人可以解决我的问题,因为我明天需要提交它。非常可观?

最佳答案

如果要隐藏列,则需要这样指定属性 Visibility

YourDataGrid.Columns[IndexOftheColumn].Visibility = Visibility.Collapsed;

如果要隐藏第一列,请说“网络ID”
dg.Columns[0].Visibility = Visibility.Collapsed;

关于c# - 如何使用MVVM在WPF中自动隐藏DataGrid列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24778677/

10-17 01:14