【问题标题】:Sending 2 controls values to a converter将 2 个控件值发送到转换器
【发布时间】:2011-09-19 22:48:24
【问题描述】:

我的应用程序中有 2 个整数上下控件。 1 代表一个时间跨度的分钟,另一个代表一个时间跨度的秒。我想将这些值绑定到时间跨度。我知道我需要为此使用转换器。但是,我还需要在任何更改事件上将这两个值都发送到转换器。因此,如果用户更改了分钟,我需要从分钟和秒中创建一个新的时间跨度。有没有办法将这两个值都发送到转换器,还是我需要在后面的代码中这样做?

这是 2 个控件的 XAML。

<extToolKit:IntegerUpDown Minimum="0" Margin="1,3,0,4" x:Name="iupApproachMin">
    <extToolKit:IntegerUpDown.Value>
        <PriorityBinding FallbackValue="50">
            <Binding Path="VehicleEntryTaskStandards.MaxEntryTimeRequirement" Converter="{StaticResource timeSpanConvertor}">
            </Binding>
        </PriorityBinding>
    </extToolKit:IntegerUpDown.Value>
</extToolKit:IntegerUpDown>
<Label>min</Label>
<extToolKit:IntegerUpDown Minimum="0" Maximum="59" Margin="1,3,0,4" FormatString="00" Value="10"></extToolKit:IntegerUpDown>
<Label>sec</Label>

这是转换器代码

[ValueConversion(typeof(TimeSpan),typeof(int))]
public class TimespanConverter:IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        int minutes = ((TimeSpan)value).Minutes;
        return minutes;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        TimeSpan resultTimeSpan = new TimeSpan();

        int minutes;
        if (int.TryParse(value.ToString(), out minutes))
        {
            resultTimeSpan = new TimeSpan(0, minutes, 0);
            return resultTimeSpan;
        }
        return DependencyProperty.UnsetValue;
    }
}

我可以让它接受一个数组或列表吗?如果是这样,如何在 xaml 中完成?

请帮忙!

【问题讨论】:

    标签: c# wpf xaml data-binding converter


    【解决方案1】:

    在 ViewModel 中使用几个属性,而不是使用 ValueConverter。

    在每个属性的设置器中都适当地更新了 TimeSpan。

    private TimeSpan _time;
    public TimeSpan Time 
    {
      get { return _time; }
      set 
      { 
        _time = value; 
        RaisePropertyChanged("Time");
      }
    }
    
    private int _minutes
    public int Minutes
    { 
      get { return _minutes; }
      set 
      {
        _minutes = value;
        CalculateTimeSpan();
        RaisePropertyChanged("Minutes");
      }
    }
    
    private int _seconds
    public int Seconds
    { 
      get { return _seconds; }
      set 
      {
        _seconds= value;
        CalculateTimeSpan();
        RaisePropertyChanged("Seconds");
      }
    }
    

    【讨论】:

    • 这应该可以。我希望我可以避免这种情况,并通过数据绑定在纯 xmal 中找到一种更优雅的方法
    • 我认为 ViewModel 是 UI 的扩展。有时,当 ViewModel 可以更快更容易阅读时,花费大量时间尝试在 Xaml 中做某事并不总是值得的。
    猜你喜欢
    • 2021-06-02
    • 2016-11-28
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    • 2011-12-02
    • 2014-04-22
    相关资源
    最近更新 更多