При использовании DataTemplate для элемента ListBox мое приложение зависает и выдает исключение в окне вывода. Подробности следуют.
Редактировать шаблон:
<DataTemplate x:Key="EditOnlyTemplate">
<Border BorderBrush="Blue" Margin="3" Padding="3" BorderThickness="2" CornerRadius="5" Background="Beige">
<StackPanel Orientation="Horizontal">
<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<TextBox Width="300" FontSize="25" Foreground="Goldenrod" Text="{Binding XPath=/doc/dob/text, Mode=OneWayToSource, UpdateSourceTrigger=PropertyChanged, diag:PresentationTraceSources.TraceLevel=High}" />
<TextBox Width="300" FontSize="25" Foreground="Blue" Text="{Binding XPath=/doc/dob/group, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Width="300" FontSize="25" Foreground="Green" Text="{Binding XPath=/doc/dob/filter, UpdateSourceTrigger=PropertyChanged}" />
<Button Content="Save" Click="btnSave_Click" Width="40" HorizontalAlignment="Left" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}}"/>
</StackPanel>
</StackPanel>
</Border>
</DataTemplate>
Я использую следующий код для обработки нажатия кнопки и переключения моего DataTemplate на мой элемент ListBox с того, который просто отображает связанные данные (т. Е. Шаблон «Подробности»), на тот, где я могу изменить связанные данные (т. Е. , "Редактировать" шаблон).
private void btnEdit_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
//command contains the list item
ContentControl itm = (ContentControl)btn.CommandParameter;
itm.ContentTemplate = this.FindResource("EditTemplate") as DataTemplate;
}
В моем EditTemplate следует отметить режим связывания первого TextBox - для него установлено значение OneWayToSource. Это то, что вызывает проблему, после нажатия кнопки «Изменить», которая переключается в этом шаблоне. Если я изменю режим на «TwoWay» (режим по умолчанию для TextBox), проблем не будет. Кроме того, если я использую копию этого шаблона в другом месте на странице, размещенной во время разработки - не с помощью кода - и не в элементе ListBox, а в ContentControl, режим OneWayToSource работает должным образом.
Исключение, выброшенное в моем сломанном сценарии, следующее:
System.Windows.Data Warning: 104 : BindingExpression (hash=48690759): At level 0 - for XmlElement.InnerText found accessor ReflectPropertyDescriptor(InnerText)
System.Windows.Data Warning: 100 : BindingExpression (hash=48690759): Replace item at level 0 with XmlElement (hash=21889970), using accessor ReflectPropertyDescriptor(InnerText)
System.Windows.Data Warning: 86 : BindingExpression (hash=48690759): Update - got raw value ''
System.Windows.Data Warning: 90 : BindingExpression (hash=48690759): Update - using final value ''
System.Wi
ndows.Data Warning: 98 : BindingExpression (hash=48690759): SetValue at level 0 to XmlElement (hash=21889970) using ReflectPropertyDescriptor(InnerText): ''
A first chance exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll
System.Windows.Data Error: 8 : Cannot save value from target back to source. BindingExpression:Path=/InnerText; DataItem='XmlDocument' (HashCode=33583636); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') InvalidOperationException:'System.InvalidOperationException: Dispatcher processing has been suspended, but messages are still being processed.
at System.ComponentModel.ReflectPropertyDescriptor.SetValue(Object component, Object value)
at MS.Internal.Data.PropertyPathWorker.SetValue(Object item, Object value)
at MS.Internal.Data.ClrBindingWorker.UpdateValue(Object value)
at System.Windows.Data.BindingExpression.UpdateSource(Object value)'
Я подозреваю, что ListBox как-то является причиной, но не могу понять почему, за исключением возможной ошибки. Я использую .Net Framework 3.5 со всеми текущими обновлениями в Windows XP. Кто-нибудь видит что-то явно не так с тем, что я пытаюсь сделать?