【发布时间】:2011-09-13 16:16:07
【问题描述】:
所以我在 wpf 中测试多重绑定,我有三个文本框,它们应该获取年、月、日,我的转换器类应该返回带有这些输入的日期..非常简单。
但在我的转换方法中,values[0] 始终未设置,即我总是得到Dependencyproperty.UnsetValue,即使给它一个初始值。
XAML
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="clr-namespace:System;assembly=mscorlib"
xmlns:src="clr-namespace:WpfApplication2"
Title="MultiBinding Demo" Width="200" Height="200">
<Window.Resources>
<src:DateConverter x:Key="myConverter" />
</Window.Resources>
<StackPanel Orientation="Horizontal">
<StackPanel.Resources>
</StackPanel.Resources>
<TextBox Name="tb1" Margin="10" Width="Auto" Height="20"></TextBox>
<TextBox Name="tb2" Margin="10" Width="20" Height="20" ></TextBox>
<TextBox Name="tb3" Width="20" Height="20" ></TextBox>
<Label Name="Date" Width="50" Height="25" Margin="5" >
<Label.Content>
<MultiBinding Converter="{StaticResource myConverter}" Mode="OneWay">
<Binding ElementName="tbl" Path="Text" />
<Binding ElementName="tb2" Path="Text" />
<Binding ElementName="tb3" Path="Text" />
</MultiBinding>
</Label.Content>
</Label>
</StackPanel>
日期转换器类
class DateConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (values[0] == DependencyProperty.UnsetValue || values[1] == DependencyProperty.UnsetValue || values[2] == DependencyProperty.UnsetValue)
{
return "";
}
else
{
int year = (int)values[0];
int month = (int)values[1];
int day = (int)values[2];
DateTime date = new DateTime(year, month, day);
return date.ToShortDateString();
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
【问题讨论】:
-
只有
values[0]未设置,还是三个都未设置?此外,这是否仅在视图最初加载或更改文本框的值将正确的值传递给转换器时发生? -
看起来它没有读取 values[0] 值,因为我在转换器类的 return 语句上放置了一个断点,它在 onload 和我编辑 value[1] 和 value[ 时被命中2] 文本框,但不是 value[0]。这将解释 dependencyproperty.unsetValue 错误,所以问题是为什么它没有读取 values 数组中的第一个值?
标签: wpf multibinding