I have a problem with the ListPicker component. I download a sample from: http://code.msdn.microsoft.com/Windows-Phone-71-Local-da2fdf80. It is compile, but when I'd like to change page (contains ListPicker), exception was thrown.
System.Windows.Markup.XamlParseException occurred
Message=Set property 'Microsoft.Phone.Controls.ListPicker.ItemCountThreshold' threw an exception. [Line: 42 Position: 63]
LineNumber=42
LinePosition=63
StackTrace:
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at PhoneApp.Views.TaskEditView.InitializeComponent()
at PhoneApp.Views.TaskEditView..ctor()
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(RuntimeConstructorInfo rtci, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Activator.InternalCreateInstance(Type type, Boolean nonPublic, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type)
at System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(AsyncCallback userCallback, PageResourceContentLoaderAsyncResult result)
at System.Windows.Navigation.PageResourceContentLoader.<>c__DisplayClass4.<BeginLoad>b__0(Object args)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
InnerException: System.NotSupportedException
Message=Cannot set read-only property 'Microsoft.Phone.Controls.ListPicker.ItemCountThreshold'.
StackTrace:
at MS.Internal.XamlMemberInfo.SetValue(Object target, Object value)
at MS.Internal.XamlManagedRuntimeRPInvokes.SetValue(XamlTypeToken inType, XamlQualifiedObject& inObj, XamlPropertyToken inProperty, XamlQualifiedObject& inValue)
at MS.Internal.XcpImports.Application_LoadComponentNative(IntPtr pContext, IntPtr pComponent, UInt32 cUriStringLength, String uriString, UInt32 cXamlStrLength, Byte* pXamlStr, UInt32 cAssemblyStrLength, String assemblyStr)
at MS.Internal.XcpImports.Application_LoadComponent(IManagedPeerBase componentAsDO, String resourceLocator, UnmanagedMemoryStream stream, UInt32 numBytesToRead, String assemblyString)
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at PhoneApp.Views.TaskEditView.InitializeComponent()
at PhoneApp.Views.TaskEditView..ctor()
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(RuntimeConstructorInfo rtci, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeConstructorInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Activator.InternalCreateInstance(Type type, Boolean nonPublic, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type)
at System.Windows.Navigation.PageResourceContentLoader.BeginLoad_OnUIThread(AsyncCallback userCallback, PageResourceContentLoaderAsyncResult result)
at System.Windows.Navigation.PageResourceContentLoader.<>c__DisplayClass4.<BeginLoad>b__0(Object args)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi, Object obj, BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture, Boolean isBinderDefault, Assembly caller, Boolean verifyAccess, StackCrawlMark& stackMark)
at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, StackCrawlMark& stackMark)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at System.Delegate.DynamicInvokeOne(Object[] args)
at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
at System.Delegate.DynamicInvoke(Object[] args)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle, Int32 nParamCount, ScriptParam[] pParams, ScriptParam& pResult)
It is my XAML page:
<local:EntityEditPage
x:Class="PhoneApp.Views.TaskEditView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
xmlns:local="clr-namespace:PhoneApp.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="edit task" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ScrollViewer>
<StackPanel>
<!-- title -->
<TextBlock Text="Title" Style="{StaticResource DefaultLabelStyle}" />
<TextBox Text="{Binding Path=Title, Mode=TwoWay}" TextWrapping="Wrap" Style="{StaticResource FormTextBox}" />
<!-- project -->
<TextBlock Text="Project" Style="{StaticResource DefaultLabelStyle}"/>
<toolkit:ListPicker x:Name="listProjects" Style="{StaticResource FormListPicker}">
<toolkit:ListPicker.FullModeItemTemplate>
<DataTemplate>
<Grid Background="Transparent" Margin="12">
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" Style="{StaticResource PhoneTextLargeStyle}" />
</Grid>
</DataTemplate>
</toolkit:ListPicker.FullModeItemTemplate>
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Name}" TextWrapping="Wrap" />
</Grid>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
</toolkit:ListPicker>
<!-- date -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock VerticalAlignment="Center" Text="Date" Style="{StaticResource DefaultLabelStyle}" />
<toolkit:DatePicker x:Name="datePicker" Style="{StaticResource FormDatePicker}" />
</StackPanel>
<StackPanel Grid.Column="1">
<TextBlock VerticalAlignment="Center" Text="Time" Style="{StaticResource DefaultLabelStyle}" />
<toolkit:TimePicker x:Name="timePicker" />
</StackPanel>
</Grid>
<!-- status -->
<TextBlock Text="Status" Style="{StaticResource DefaultLabelStyle}"/>
<toolkit:ListPicker x:Name="listStatus" ListPickerMode="Normal" SelectedItem="{Binding Status, Mode=TwoWay}">
<toolkit:ListPicker.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</toolkit:ListPicker.ItemTemplate>
</toolkit:ListPicker>
<!-- description -->
<TextBlock Text="Description" Style="{StaticResource DefaultLabelStyle}" />
<TextBox Text="{Binding Path=Description, Mode=TwoWay}" Height="285" TextWrapping="Wrap" AcceptsReturn="True" Style="{StaticResource FormTextBox}" />
</StackPanel>
</ScrollViewer>
</Grid>
</Grid>
<!--Sample code showing usage of ApplicationBar-->
<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar>
<shell:ApplicationBarIconButton IconUri="/icons/appbar.check.rest.png" Text="button" Click="OnOK"/>
<shell:ApplicationBarIconButton IconUri="/icons/appbar.cancel.rest.png" Text="button" Click="OnCancel"/>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
</local:EntityEditPage>
Related
And if it is, what control would be the best bet? DataGrid that has the virtualization or something else? This happens very very rarely so trial and error is not an option. Portion of my xaml and converter used is in the end.
This happens sometimes (maybe 1/1000?) when DataGrid's itemssource (ICollectionView) is refreshed.
2017-10-06 09:00:35: myapp.exe Error: 0 : Unhandled exception.
System.ArgumentException: Height must be non-negative.
at System.Windows.Rect.set_Height(Double value)
at
System.Windows.Controls.VirtualizingStackPanel.ExtendViewport(IHierarchicalVirtualizationAndScrollInfo
virtualizationInfoProvider, Boolean isHorizontal, Rect viewport,
VirtualizationCacheLength cacheLength, VirtualizationCacheLengthUnit
cacheUnit, Size stackPixelSizeInCacheBeforeViewport, Size
stackLogicalSizeInCacheBeforeViewport, Size
stackPixelSizeInCacheAfterViewport, Size
stackLogicalSizeInCacheAfterViewport, Size stackPixelSize, Size
stackLogicalSize, Int32& itemsInExtendedViewportCount)
at
System.Windows.Controls.VirtualizingStackPanel.IsExtendedViewportFull()
at
System.Windows.Controls.VirtualizingStackPanel.ShouldItemsChangeAffectLayoutCore(Boolean
areItemChangesLocal, ItemsChangedEventArgs args)
at
System.Windows.Controls.VirtualizingPanel.OnItemsChangedInternal(Object
sender, ItemsChangedEventArgs args)
at System.Windows.Controls.Panel.OnItemsChanged(Object sender,
ItemsChangedEventArgs args)
at
System.Windows.Controls.ItemContainerGenerator.OnItemAdded(Object
item, Int32 index)
at
System.Windows.Controls.ItemContainerGenerator.OnCollectionChanged(Object
sender, NotifyCollectionChangedEventArgs args)
at
System.Windows.WeakEventManager.ListenerList`1.DeliverEvent(Object
sender, EventArgs e, Type managerType)
at System.Windows.WeakEventManager.DeliverEvent(Object sender,
EventArgs args)
at
System.Collections.ObjectModel.ReadOnlyObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs
args)
at
System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs
e)
at
System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32
index, T item)
at MS.Internal.Data.CollectionViewGroupInternal.Insert(Object item,
Object seed, IComparer comparer)
at MS.Internal.Data.CollectionViewGroupRoot.AddToSubgroup(Object
item, LiveShapingItem lsi, CollectionViewGroupInternal group, Int32
level, Object name, Boolean loading)
at MS.Internal.Data.CollectionViewGroupRoot.AddToSubgroups(Object
item, LiveShapingItem lsi, CollectionViewGroupInternal group, Int32
level, Boolean loading)
at System.Windows.Data.ListCollectionView.AddItemToGroups(Object
item, LiveShapingItem lsi)
at
System.Windows.Data.ListCollectionView.ProcessCollectionChangedWithAdjustedIndex(NotifyCollectionChangedEventArgs
args, Int32 adjustedOldIndex, Int32 adjustedNewIndex)
at
System.Collections.ObjectModel.ObservableCollection`1.OnCollectionChanged(NotifyCollectionChangedEventArgs
e)
at
System.Collections.ObjectModel.ObservableCollection`1.InsertItem(Int32
index, T item)
at
MS.Internal.Data.EnumerableCollectionView.LoadSnapshotCore(IEnumerable
source)
at
MS.Internal.Data.EnumerableCollectionView.LoadSnapshot(IEnumerable
source)
at System.Windows.Data.CollectionView.RefreshInternal()
XAML:
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition Name="SelectedObjectsRowDefinition">
<RowDefinition.Height>
<MultiBinding Converter="{StaticResource GridRowHeightConverter}">
<Binding ElementName="SelectedObjectsExpander" Path="IsExpanded" />
<Binding Path="IsSelectedObjectsVisible" />
<Binding ElementName="SelectedObjectsGrid" Path="Items.Count" />
</MultiBinding>
</RowDefinition.Height>
</RowDefinition>
<RowDefinition Name="SelectedSwitchesRowDefinition">
<RowDefinition.Height>
<MultiBinding Converter="{StaticResource GridRowHeightConverter}">
<Binding ElementName="SelectedSwitchesExpander" Path="IsExpanded" />
<Binding Path="IsSelectedSwitchesVisible" />
<Binding ElementName="SelectedSwitchesGrid" Path="Items.Count" />
</MultiBinding>
</RowDefinition.Height>
</RowDefinition>
<RowDefinition Name="SelectionsRowDefinition">
<RowDefinition.Height>
<MultiBinding Converter="{StaticResource GridRowHeightConverter}">
<Binding ElementName="SelectionsExpander" Path="IsExpanded" />
<Binding Path="IsSelectionSetsVisible" />
<Binding ElementName="SelectionSetsGrid" Path="Items.Count" />
</MultiBinding>
</RowDefinition.Height>
</RowDefinition>
</Grid.RowDefinitions>
<Expander Grid.Row="0" Header="{DynamicResource XpStrSelectedObjects}" x:Name="SelectedObjectsExpander" AutomationProperties.AutomationId="SelectedObjectsExp"
IsExpanded="{Binding IsSelectedObjectsExpanded}" Visibility="{Binding IsSelectedObjectsVisible, Converter={StaticResource BoolToVisibilityConverter}}">
<Grid Margin="15,0,0,0">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Background="White"
Visibility="{Binding ShowSelectedObjectsInfoPanel, Converter={StaticResource BoolToVisibilityConverter}}" Margin="0,0,4,0">
<StackPanel Margin="0,0,4,0">
<TextBlock Text="{Binding SelectedObjectsInfoPanelText}"
FontStyle="Italic" HorizontalAlignment="Center" VerticalAlignment="Center" />
<Button HorizontalAlignment="Center" Content="{StaticResource NisStrShowAnyway}"
Visibility="{Binding IsFetchObjectsAnywayVisible, Converter={StaticResource BoolToVisibilityConverter}}"
Command="{ui:CommandHandler FetchObjectsAnyway}"
AutomationProperties.AutomationId="ShowAnywayBtn"/>
</StackPanel>
</Grid>
<DataGrid Name="SelectedObjectsGrid" AutomationProperties.AutomationId="SelectedObjectsDgd"
Visibility="{Binding ShowSelectedObjectsInfoPanel, Converter={StaticResource BoolNegationToVisibilityConverter}}"
ItemsSource="{Binding SelectedObjectItems}"
SelectionMode="Extended"
CanUserAddRows="False"
AutoGenerateColumns="False"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.IsVirtualizingWhenGrouping="True"
VirtualizingPanel.VirtualizationMode="Standard"
VerticalAlignment="Top"
IsReadOnly="True"
Grid.Row="0" Margin="0,0,4,0">
Convert-method of IMultivalueConverter used in XAML above:
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
bool isExpanded = (bool)values[0];
bool isVisible = (bool)values[1];
int itemsCount = (int)values[2];
if (!isVisible || !isExpanded || itemsCount == 0)
return System.Windows.GridLength.Auto;
else
return new System.Windows.GridLength(1, System.Windows.GridUnitType.Star);
}
catch (Exception)
{
return new System.Windows.GridLength(1, System.Windows.GridUnitType.Star);
}
}
I have a GroupBox whose IsEnabled Property is set via a property on the ViewModel as under:-
<GroupBox>
<Canvas IsEnabled="{Binding CurrentRec.Current_Selected_Category.NoBonus,Converter={StaticResource TFC}}">
<Label Content="Amount:" Width="55" Canvas.Left="9" Canvas.Top="-2"/>
<TextBox x:Name="txtBonusAmount" Width="76" Canvas.Left="12" Canvas.Top="20" Text="Some text"/>
<Label Content="Bonus:" Canvas.Top="38" Width="54" Canvas.Left="10"/>
<TextBox x:Name="txtBonus" Width="76" Canvas.Left="13" Canvas.Top="58" Text="Some Text"/>
</Canvas>
<Groupbox>
There are more than one properties in my viewmodel affecting the IsEnabled property of Canvas.How do i specify those additional properties against the IsEnabled property of Canvas?
Use a MultiBinding with a converter:
<GroupBox>
<GroupBox.Resources>
<local:MultiConverter x:Key="conv" />
</GroupBox.Resources>
<Canvas>
<Canvas.IsEnabled>
<MultiBinding Converter="{StaticResource conv}">
<Binding Path="CurrentRec.Current_Selected_Category.NoBonus" />
<Binding Path="TheOtherProperty" />
</MultiBinding>
</Canvas.IsEnabled>
<Label Content="Amount:" Width="55" Canvas.Left="9" Canvas.Top="-2"/>
<TextBox x:Name="txtBonusAmount" Width="76" Canvas.Left="12" Canvas.Top="20" Text="Some text"/>
<Label Content="Bonus:" Canvas.Top="38" Width="54" Canvas.Left="10"/>
<TextBox x:Name="txtBonus" Width="76" Canvas.Left="13" Canvas.Top="58" Text="Some Text"/>
</Canvas>
</GroupBox>
The converter class should implement the IMultiValueConverter interface and return a bool from the Convert method:
public class MultiConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
bool noBonus = System.Convert.ToBoolean(values[0]);
bool theOtherSourceProperty = System.Convert.ToBoolean(values[1]);
//..
return noBonus && theOtherSourceProperty;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
I am following the example posted by Telerik on how to show/hide columns in their RadGridView control, as shown here:
<StackPanel x:Name="CustomizeGrid" Background="Transparent" Orientation="Horizontal">
<ListBox ItemsSource="{Binding Columns, ElementName=WorklistGridView}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Header}" IsChecked="{Binding IsVisible, Mode=TwoWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<telerik:RadGridView x:Name="WorklistGridView" AutoGenerateColumns="False" RowIndicatorVisibility="Collapsed" IsReadOnly="True" SelectionMode="Multiple"
CanUserSelect="False" IsSynchronizedWithCurrentItem="False" ItemsSource="{Binding Mode=OneWay}" IsFilteringAllowed="True">
<telerik:RadGridView.Columns>
<telerik:GridViewSelectColumn x:Name="Select" IsResizable="False" />
<telerik:GridViewDataColumn Header="Status" DataMemberBinding="{Binding OrderStatusDescription}"/>
<telerik:GridViewDataColumn Header="Patient Name" DataMemberBinding="{Binding PatientName}"/>
But the example is not compiling correctly. The problem is here: CheckBox `Content="{Binding Header}" The main error listed is: Value does not fall within the expected range.
I'm not sure why this is happening. I'll try to post the rest of the error below. Does anyone else have this working, or have any ideas what's up?
System.InvalidOperationException
An unhandled exception was encountered while trying to render the current silverlight project on the design surface. To diagnose this failure, please try to run the project in a regular browser using the silverlight developer runtime. at
Microsoft.Windows.Design.Platform.SilverlightViewProducer.OnUnhandledException(Object sender, ViewUnhandledExceptionEventArgs e) at Microsoft.Expression.Platform.Silverlight.SilverlightPlatformSpecificView.OnUnhandledException(Object sender, ViewUnhandledExceptionEventArgs args) at Microsoft.Expression.Platform.Silverlight.Host.SilverlightImageHost.<>c_DisplayClass1.b_0(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
System.ArgumentException Value does not fall within the expected range. at MS.Internal.XcpImports.CheckHResult(UInt32 hr) at MS.Internal.XcpImports.SetValue(IManagedPeerBase obj, DependencyProperty property, DependencyObject doh) at MS.Internal.XcpImports.SetValue(IManagedPeerBase doh, DependencyProperty property, Object obj) at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value) at System.Windows.DependencyObject.SetEffectiveValue(DependencyProperty property, EffectiveValueEntry& newEntry, Object newValue) at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation) at System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp) at System.Windows.Data.BindingExpression.SendDataToTarget() at System.Windows.Data.BindingExpression.SourceAcquired() at System.Windows.Data.BindingExpression.System.Windows.IDataContextChangedListener.OnDataContextChanged(Object sender, DataContextChangedEventArgs e) at System.Windows.Data.BindingExpression.DataContextChanged(Object sender, DataContextChangedEventArgs e) at System.Windows.DataContextChangedEventHandler.Invoke(Object sender, DataContextChangedEventArgs e) at System.Windows.FrameworkElement.OnDataContextChanged(DataContextChangedEventArgs e) at System.Windows.FrameworkElement.OnTreeParentUpdated(DependencyObject newParent, Boolean bIsNewParentAlive) at System.Windows.DependencyObject.UpdateTreeParent(IManagedPeer oldParent, IManagedPeer newParent, Boolean bIsNewParentAlive, Boolean keepReferenceToParent) at MS.Internal.FrameworkCallbacks.ManagedPeerTreeUpdate(IntPtr oldParentElement, IntPtr parentElement, IntPtr childElement, Byte bIsParentAlive, Byte bKeepReferenceToParent, Byte bCanCreateParent)
I managed to replicate your issue but I receive different exception ("Element is already the child of another element"). I think the reason can be the same so see if it helps.
A little debugging shows that when SelectionMode is set to Multiple then the Header of GridViewSelectColumn becomes a CheckBox. This means that you're trying to add same CheckBox to both column header and CheckBox content inside your ListBox. Just try to remove SelectionMode and see if you have the same issue or not.
If that's the case then you can fix issue by adding a converter to CheckBox.Content binding that passes through only strings. For example:
public class HeaderConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string)
return value;
return string.Empty;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
Then in XAML:
<ListBox ItemsSource="{Binding Columns, ElementName=WorklistGridView}">
<ListBox.Resources>
<local:HeaderConverter x:Key="headerConverter" />
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Header, Converter={StaticResource headerConverter}}"
IsChecked="{Binding IsVisible, Mode=TwoWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
I am following the example posted by Telerik on how to show/hide columns in their RadGridView control, as shown here:
<StackPanel x:Name="CustomizeGrid" Background="Transparent" Orientation="Horizontal">
<ListBox ItemsSource="{Binding Columns, ElementName=WorklistGridView}">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Header}" IsChecked="{Binding IsVisible, Mode=TwoWay}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<telerik:RadGridView x:Name="WorklistGridView" AutoGenerateColumns="False" RowIndicatorVisibility="Collapsed" IsReadOnly="True" SelectionMode="Multiple"
CanUserSelect="False" IsSynchronizedWithCurrentItem="False" ItemsSource="{Binding Mode=OneWay}" IsFilteringAllowed="True">
<telerik:RadGridView.Columns>
<telerik:GridViewSelectColumn x:Name="Select" IsResizable="False" />
<telerik:GridViewDataColumn Header="Status" DataMemberBinding="{Binding OrderStatusDescription}"/>
<telerik:GridViewDataColumn Header="Patient Name" DataMemberBinding="{Binding PatientName}"/>
But the example is not compiling correctly. The problem is here:
CheckBox Content="{Binding Header}"
The main error listed is: Value does not fall within the expected range.
I'm not sure why this is happening. I'll try to post the rest of the error below. Does anyone else have this working, or have any ideas what's up?
System.InvalidOperationException
An unhandled exception was encountered while trying to render the current silverlight project on the design surface. To diagnose this failure, please try to run the project in a regular browser using the silverlight developer runtime.
at Microsoft.Windows.Design.Platform.SilverlightViewProducer.OnUnhandledException(Object sender, ViewUnhandledExceptionEventArgs e)
at Microsoft.Expression.Platform.Silverlight.SilverlightPlatformSpecificView.OnUnhandledException(Object sender, ViewUnhandledExceptionEventArgs args)
at Microsoft.Expression.Platform.Silverlight.Host.SilverlightImageHost.<>c_DisplayClass1.b_0(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
System.ArgumentException
Value does not fall within the expected range.
at MS.Internal.XcpImports.CheckHResult(UInt32 hr)
at MS.Internal.XcpImports.SetValue(IManagedPeerBase obj, DependencyProperty property, DependencyObject doh)
at MS.Internal.XcpImports.SetValue(IManagedPeerBase doh, DependencyProperty property, Object obj)
at System.Windows.DependencyObject.SetObjectValueToCore(DependencyProperty dp, Object value)
at System.Windows.DependencyObject.SetEffectiveValue(DependencyProperty property, EffectiveValueEntry& newEntry, Object newValue)
at System.Windows.DependencyObject.UpdateEffectiveValue(DependencyProperty property, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, ValueOperation operation)
at System.Windows.DependencyObject.RefreshExpression(DependencyProperty dp)
at System.Windows.Data.BindingExpression.SendDataToTarget()
at System.Windows.Data.BindingExpression.SourceAcquired()
at System.Windows.Data.BindingExpression.System.Windows.IDataContextChangedListener.OnDataContextChanged(Object sender, DataContextChangedEventArgs e)
at System.Windows.Data.BindingExpression.DataContextChanged(Object sender, DataContextChangedEventArgs e)
at System.Windows.DataContextChangedEventHandler.Invoke(Object sender, DataContextChangedEventArgs e)
at System.Windows.FrameworkElement.OnDataContextChanged(DataContextChangedEventArgs e)
at System.Windows.FrameworkElement.OnTreeParentUpdated(DependencyObject newParent, Boolean bIsNewParentAlive)
at System.Windows.DependencyObject.UpdateTreeParent(IManagedPeer oldParent, IManagedPeer newParent, Boolean bIsNewParentAlive, Boolean keepReferenceToParent)
at MS.Internal.FrameworkCallbacks.ManagedPeerTreeUpdate(IntPtr oldParentElement, IntPtr parentElement, IntPtr childElement, Byte bIsParentAlive, Byte bKeepReferenceToParent, Byte bCanCreateParent)
Morning Guys,
I have a few ComboBoxes bound to List of TimeSpan. I am formatting the TimeSpans using IValueConverter and ItemTemplate. I was wondering if there were an easier way to format the TimeSpans. Here's what I'm currently doing.
public class TimeSpanConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value == null)
return string.Empty;
TimeSpan t = TimeSpan.MinValue;
TimeSpan.TryParse(value.ToString(), out t);
return "{0:00}:{1:00}".F(t.Hours,t.Minutes);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return TimeSpan.Parse(value.ToString());
}
#endregion
}
<Canvas>
<Canvas.Resources>
<bc:TimeSpanConverter x:Key="ts" />
<DataTemplate x:Key="TimeSpanTemplate">
<TextBlock Text="{Binding ., Converter={StaticResource ts}}" />
</DataTemplate>
</Canvas.Resources>
<TextBlock Canvas.Left="6"
Canvas.Top="6"
Height="21"
Name="textBlock4"
Text="Begin"
Width="40" />
<TextBlock Canvas.Left="81"
Canvas.Top="6"
Height="21"
Name="textBlock5"
Text="End"
Width="40" />
<ComboBox Canvas.Left="7"
Canvas.Top="25"
Height="23"
Name="TimeBeginCombo"
ItemTemplate="{StaticResource TimeSpanTemplate}"
SelectedItem="{Binding TimeBegin}"
Width="68" />
<ComboBox Canvas.Left="81"
Canvas.Top="25"
Height="23"
Name="TimeEndCombo"
ItemTemplate="{StaticResource TimeSpanTemplate}"
SelectedItem="{Binding TimeEnd}"
Width="68" />
</Canvas>
</GroupBox>
Is what you're binding to of type TimeSpan? If so, then the converter can be much simpler
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (!(value is TimeSpan))
return string.Empty;
TimeSpan t = (TimeSpan)value;
return "{0:00}:{1:00}".F(t.Hours,t.Minutes);
}
And also, a general remark - are you sure you need to layout your UI on a Canvas and using absolute coordinates? :)