ValueConverters.Net的使用
在B站上看到的内容。记录下来
获取
在NuGet中搜索ValueConverters. 找到的第一个就是:
https://github.com/thomasgalliker/ValueConverters.NET
使用步骤:
1. 引用
2. 在Resource中声明它. 例如:
1 2 3
| <Window.Resources> <conv:BoolToVisibilityConverter x:Key="BoolToVisibilityInv" IsInverted="True" FalseValue="Collapsed"/> </Window.Resources>
|
3. 使用:
1 2 3 4
| <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center"> <CheckBox x:Name="chkHasRead" Content="我已阅读" Margin="10"/> <TextBlock x:Name="txtLabel1" Text="Hellow" Margin="10" Visibility="{Binding ElementName=chkHasRead, Path=IsChecked, Converter={StaticResource BoolToVisibilityInv}}" /> </StackPanel>
|
上述代码中, 当chkHasRead.IsCheck
的true被转换为Collapsed
.
4. 串联使用多个converter
1 2 3 4 5
| <conv:ValueConverterGroup x:Key="value2"> <conv:StringIsNotNullOrEmptyConverter/> <conv:BoolInverter/> <conv:BoolToVisibilityConverter/> </conv:ValueConverterGroup>
|
上面是一个组合的ValueConverter. 它顺序检查:
- 检查字符串是否为空
- 将上一步的值取反
- 转换为Visibility
要求编辑框的内容的长度要做5-16个字符之间. 否则显示错误信息:
1 2 3 4 5 6 7 8 9
| <conv:ValueConverterGroup x:Key="converter3"> <conv:IsInRangeConverter MinValue="5" MaxValue="16"/> <conv:BoolInverter/> <conv:BoolToVisibilityConverter/> </conv:ValueConverterGroup>
<TextBox x:Name="password"/> <TextBox x:Name="passWarn" Text="Invalid password length" Visibility="{Binding ElementName=password, Path=Text.Length, Converter={StaticResource converter3}}"/>
|
DebugConverter