我正在编写一个WPF用户控件,该控件显示带有多个页面的动态生成的TabControl,每个页面依次包含动态生成的控件(TextBox,Checkbox等)的列表。
我想根据用户是否具有查看权限来设置TextBox和CheckBox控件的可见性。此权限是每个控件ViewModel的值(“ VisibleBy”)和整个UserControl ViewModel的属性(“ UserRole”)的组合。我刚刚开始使用WPF,但是标准方法似乎是使用ValueConvertor-但是我不明白如何编写一个可以合并/访问不同属性(VisibleBy和UserRole)的属性,因为它们存在于不同级别在我的ViewModel层次结构中。
这是我绑定到ViewModel的XAML的一部分:
<TabControl ItemsSource="{Binding VariableData.Pages}" SelectedIndex="0">
<!-- this is the header template-->
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}" FontWeight="Bold"/>
</DataTemplate>
</TabControl.ItemTemplate>
<!-- this is the tab content template-->
<TabControl.ContentTemplate>
<DataTemplate>
<StackPanel>
<ListBox Grid.IsSharedSizeScope="True"
ItemsSource="{Binding Variables}"
ItemTemplateSelector="{StaticResource templateSelector}">
</ListBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Button Content="Cancel" />
<Button Content="Submit"
Command="{Binding DataContext.CommitChangesCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type TabControl}}}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
我还需要扩展将来控制可见性的变量的数量,因为这还取决于它在应用程序中的使用位置。
您可以尝试IMultiValueConverter并使用Multibinding。
<Window x:Class="ItemsControl_Learning.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ItemsControl_Learning"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:VisibilityConverter x:Key="conv" />
</Window.Resources>
<Grid>
<Button Content="Test">
<Button.Visibility>
<MultiBinding Converter="{StaticResource conv}">
<Binding Path="Role" />
<Binding Path="OtherProp" />
</MultiBinding>
</Button.Visibility>
</Button>
</Grid>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
class MainViewModel
{
private string role;
public string Role
{
get { return role; }
set { role = value; }
}
private string otherProp;
public string OtherProp
{
get { return otherProp; }
set { otherProp = value; }
}
public MainViewModel()
{
Role = "Admin";
OtherProp = "Fail";
}
}
class VisibilityConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values[0].ToString().Equals("Admin") && values[1].ToString().Equals("Pass"))
{
return Visibility.Visible;
}
else
{
return Visibility.Collapsed;
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
在该Convert(...)
方法中,values
数组中不同输入的顺序与MultiBinding.Bindings
集合中的顺序相同。
在这个例子中values[0]
包含了Role
财产,values[1]
将是OtherProp
因为这是他们得到了插在XAML的顺序
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句