c# - 更改 XAML 中的绑定(bind)值

标签 c# wpf xaml data-binding

我需要在 XAML 中进行一些复杂的绑定(bind)。我有一个 DependencyProperty typeof(double);我们将其命名为 SomeProperty。在我的控件的 XAML 代码中的某处,我需要使用整个 SomeProperty 值,某处只使用一半,某处 SomeProperty/3,等等。

我该如何做:

<SomeControl Value="{Binding ElementName=MyControl, Path=SomeProperty} / 3"/>

:)

期待。

最佳答案

使用除法ValueConverter :

public class DivisionConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        int divideBy = int.Parse(parameter as string);
        double input = (double)value;
        return input / divideBy;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
<!-- Created as resource -->
<local:DivisionConverter x:Key="DivisionConverter"/>

<!-- Usage Example -->
<TextBlock Text="{Binding SomeProperty, Converter={StaticResource DivisionConverter}, ConverterParameter=1}"/>
<TextBlock Text="{Binding SomeProperty, Converter={StaticResource DivisionConverter}, ConverterParameter=2}"/>
<TextBlock Text="{Binding SomeProperty, Converter={StaticResource DivisionConverter}, ConverterParameter=3}"/>

关于c# - 更改 XAML 中的绑定(bind)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5710521/

相关文章:

c# - 尝试使用 json.Net 反序列化 json 字符串时出错

c# - 为什么 DispatcherTimer 在某个随机时间后停止触发?

c# - 在 WPF DataGrid 中显示 "Display name"而不是字段名称

c# - WPF C# 如何使用 x :array 在 WPF 中的自定义模型类中绑定(bind)和设置列表

c# - 在 xaml 中声明数组的数组

c# - 身份角色未添加到用户

c# - 插入换行而不是 CRLF

c# - 使用按日期/月份分组的日期期间操作列表中的数据

c# - 为自定义控件设置样式

.net - 在 Microsoft.Win32.OpenFileDialog 上调用 ShowDialog 时出现异常