我正在尝试将TextBox绑定到Calendar控件上的选定日期,并且在初始化时,没有问题。问题是,当我更改所选日期之后,TextBox保持其初始值(今天)。我尝试了3种方法,包括简单地返回TextBox.Text = Calendar.DisplayDate.ToString(),但问题仍然存在。
是否有人知道导致这种情况的原因或解决方法?
请注意,方法2中的PropertyChanged不为空。
我的代码如下,实现了另外两种方法:
XAML:
<Calendar Grid.Column="1" Height="170" HorizontalAlignment="Left" Name="calStart" VerticalAlignment="Top" Width="180" IsTodayHighlighted="False" SelectedDatesChanged="CalStartSelectedDatesChanged">
<Calendar.CalendarDayButtonStyle>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding Converter={StaticResource conv}}" Value="1">
<Setter Property="Button.Background" Value="LightGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</Calendar.CalendarDayButtonStyle>
</Calendar>
<TextBox Height="23" HorizontalAlignment="Left" Margin="34,33,0,0" Text="{Binding StartBindProp, Mode=OneWay}" Name="txtStartDate" VerticalAlignment="Top" Width="120" Grid.Column="1" Grid.Row="1" />
C# 方法1:
private void CalStartSelectedDatesChanged(object sender, SelectionChangedEventArgs e)
{
StartBindProp = calStart.DisplayDate.ToString();
}
public string StartBindProp
{
get { return (string)GetValue(StartBindPropProperty); }
set { SetValue(StartBindPropProperty, value); }
}
// Using a DependencyProperty as the backing store for StartBindProp. This enables animation, styling, binding, etc...
public static readonly DependencyProperty StartBindPropProperty =
DependencyProperty.Register("StartBindProp", typeof(string), typeof(MainControl), new UIPropertyMetadata(""));
方法2:
private void CalEndSelectedDatesChanged(object sender, SelectionChangedEventArgs e)
{
EndBind = calEnd.DisplayDate.ToString();
}
private string m_EndBind = "endtest";
public string EndBind
{
get { return m_EndBind; }
set
{
m_EndBind = value;
if (null != PropertyChanged)
{
PropertyChanged(this, new PropertyChangedEventArgs("EndBind"));
}
}
}
感谢您的帮助!
编辑: 以下xaml具有相同的问题(并且显然将日历呈现为只读):
<TextBox Text="{Binding ElementName=calStart, Path=DisplayDate, Mode=OneWay}" />
答案 0 :(得分:1)
使用Calendar.SelectedDate
(或SelectedDates
,如果是多个)代替DisplayDate
我相信DisplayDate
用于确定哪个日期在日历中具有“选定”轮廓(因为可以选择多个日期),而SelectedDate
是控件的实际值
您可以在日历控件here
上找到MSDN文档