Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all 18858 articles
Browse latest View live

[Bug Fix] Problem on tree view UI change after filter method called by thread

$
0
0

When I unchecked the Green check box option and click the "Set item to red" button, it able from "No Error" UI change to display tree nodes.

However, if I try to repeat those steps, unchecked green check box and call the methods without click the button, it unable to change the UI from "No Error" to display tree nodes.

I have try to mock the situation by implement this

//start test
            Thread t = new Thread(() => {
                Thread.Sleep(10000);
                List<uint> DataNotificationList = new List<uint>()
            {
                2,
                6,
                9
            };

                foreach (uint studentId in DataNotificationList)
                {
                    foreach (var course in treeListViewModel.Courses)
                    {
                        Student student;

                        if (course.Students.TryGetValue(studentId, out student))
                        {
                            student.ExecuteStrategy(hasError());
                            break;
                        }
                    }
                }

                FilterTree();
                UpdateTreeViewParentNode();
                UpdateErrorList();
                UpdateErrorSummary();
            });
            t.Start();
            //end test

I am not sure whether it is UI thread problem or something else, so far I didn't found any error occurred.


Source Code





Datagrid SelectedItems in MVVM

$
0
0

Hi,

I have written the following for retrieving the datagrid selecteditems, which is a readonly property .

namespace Wpf.Behaviours
{
    using System.Collections;
    using System.Windows;
    using System.Windows.Controls;

    public static class DataGridSelectedItems
    {

        public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.RegisterAttached("SelectedItems", typeof(IList), typeof(DataGridSelectedItems), new PropertyMetadata(OnSelectionChanged));

      
        #region SelectedItems

        public static void SetSelectedItems(DependencyObject frameworkElement, IList value)
        {
            frameworkElement.SetValue(SelectedItemsProperty, value);
        }

        public static IList GetSelectedItems(DependencyObject frameworkElement)
        {
            return (IList)frameworkElement.GetValue(SelectedItemsProperty);
        }

        #endregion

        private static void OnSelectionChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            var datagrid = (DataGrid)dependencyObject;

            if ((bool)e.NewValue)
            {
                datagrid.SelectionChanged += new SelectionChangedEventHandler(datagrid_SelectionChanged);
            }
            else
            {
                datagrid.SelectionChanged -= datagrid_SelectionChanged;
            }
        }

        private static void datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var datagrid = sender as DataGrid;
            UpdateSelection(datagrid);
        }

        private static void UpdateSelection(DataGrid datagrid)
        {
            if (datagrid != null)
            {
                datagrid.SetCurrentValue(SelectedItemsProperty, datagrid.SelectedItems);
            }
        }
    }
}

Binding in xaml is as follows

<Datagrid 

Behaviours:DataGridSelectedItems.SelectedItems="{Binding SelectedItems, Mode=OneWayToSource}"/>

The selecteditems property setter is being called only once and that too on startup, its not getting called on selection change. May someone help me by correcting my code.

Thanking you

Ramakrishna


Ramakrishna




Getting type of of PathSegmentCollection elements.

$
0
0

Hello,

I need to interate over the segments of a PathSegmentCollection.

However, I do not know what type of segment types the collection will have, so I must to test the type for each one and make the apropriated processing.

How can I "switch" over all possible PathSegment derived object types?

Here they are:

http://msdn.microsoft.com/en-us/library/system.windows.media.pathsegment(v=vs.110).aspx#inheritanceContinued

Thank you,

Igor.


.NET Software developer for industrial internet and automation system.

Handling various Keys in KeyDown event of textbox

$
0
0

Hi,

I want to handle various keys on my key down event for a textbox.

So the scenario is that i have a textbox and therein if all the text is selected, i can press the Del or Back keys and the text gets deleted. I can even press numeric and alphabets keys and the same thing should happen.

I cannot press Modifiers Keys viz. Ctrl,Alt,Shift,Shift-Tab,etc.... Also the up and down arrow keys.

Is there any efficient and a minimal way to handle this or i will have to write the code for checking each and every key by using e.key ??

Thanks,

Abdi

Data Virtualization solutions

$
0
0

During a long research of this topic it seems as if not many developers are concerned with this. Latest .NET does not have it implemented, I have not found a commercial solution except one from Telerik and regarding open source versions:

The best solutions I have found are from Bea Stollnitz
http://bea.stollnitz.com/blog/?p=344
and from  Weifen Luo
https://datavirtualization.codeplex.com/

but latest version is from April 2010, with same problems of selection and sorting. Reading the number of downloads I don't even need to ask if you are using this. Do you have a need for data virtualization and what are you using for this? There must be something newer and better after more than 4.5 years.

Remove DataGrid Column using context menu on Column Header

$
0
0

Hi,

I want to implement context menu for DataGridColumnHeader with just one menu item "Remove Column". The menu item name is self explanatory i.e. using this context menu Item, I want to remove the DataGridColumn from the Grid. How this can be achieved in WPF way?

I have following xaml code for creating context menu.

<ContextMenu x:Key="headerContextMenu"><MenuItem Header="Remove Column" Click="item_Click"/></ContextMenu><Style TargetType="DataGridColumnHeader"><Setter Property="ContextMenu" Value="{StaticResource headerContextMenu}"/></Style>

What I'm not able to figure out is what code I should write to remove the datagrid column? I cannot get reference of datagridcolumnheader/datagridcolumn inside menu item click event and also Visual tree of Context Menu and DataGrid are different.

Regards,


Krunal C



App.config returning null

$
0
0

Hi,

I have a class library and I'm trying to bring in a test key value, but it's returning null and I can't seem to get it working.

string returnValue = ConfigurationManager.AppSettings["testkey"];
<?xml version="1.0" encoding="utf-8" ?><configuration><appsettings><add key="testkey" value="testvalue"/></appsettings></configuration>
Am I doing something wrong?


Control doesn't the whole space as it should!!

$
0
0

Hi everyone,

I have two list controls which are placed in a grid in two adjacent columns.

The second list may or may not have items. If it doesn't then it's visibility is collapsed so that the first list can occupy the whole space.

This is the code:

<Grid><Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="Auto"/><ListBox
                         HorizontalAlignment="Stretch"
                         Grid.Column="0"
                         DockPanel.Dock="Top"
                         FontSize="10pt"
                     ScrollViewer.VerticalScrollBarVisibility="Auto"
                         /><ListBox
                             Grid.Column="1" HorizontalAlignment="Right"
 Visibility = "{Binding Path=HasItems,
RelativeSource={RelativeSource Self},
                             Converter={StaticResource BoolToVisibilityConverter}}"

                             /></Grid>

But I can see the second list space still present when I run the application. That is even though there are no items in the second list, the first list still doesnt occupy the whole space. But if I some how refresh that space, by loading some other data in that list etc I can see it works as expected.

It doesnt work first time when I run the application.

Thank you.


Please Mark as Answered If this answers your question OrUnMark as Answered if it did not.
Happy to Help :)
My Site


WPF DataGrid binding

$
0
0
   

Hi,

I would like to bind data from an XmlDataProvider to a datagrid.

I've got an xml data like this bellow and I would like to bind a datagridcomboboxcolum to list all vendors - Surname for a given project(Datagrid context is already binded to combobox that selects a project).

<?xml version="1.0" encoding="utf-8" ?><ProjectList><SingleProject id="1" name="TRP"><LanguageList><Language id ="1"><TargetCode>en-gb</TargetCode><TargetLanguageName>English</TargetLanguageName><VendorList><Vendor id="1"><Name>Karin</Name><Surname>AAA</Surname><GridPath>e:\stuff</GridPath></Vendor><Vendor id="2"><Name>Kate</Name><Surname>BBB</Surname><GridPath>e:\stuffss</GridPath></Vendor></VendorList></Language></LanguageList></SingleProject></ProjectList>
 Here is an XAML code:

<UserControl x:Class="Test"><UserControl.Resources><XmlDataProvider x:Key="XmlData" Source="../!setup.xml"/></UserControl.Resources><Grid Style="{StaticResource ContentRoot}"><Grid Margin="10,10,722,280"><TextBlock Text="Select:" Style="{StaticResource Heading2}" Margin="0,0,34,105" /><ComboBox x:Name="cmbSelect" ItemsSource="{Binding Source={StaticResource XmlData}, XPath=/ProjectList/*}" IsSynchronizedWithCurrentItem="True" HorizontalAlignment="Left" Margin="0,32,0,0" VerticalAlignment="Top" Width="123" Height="28"><ComboBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding XPath=@name}" /></DataTemplate></ComboBox.ItemTemplate></ComboBox></Grid><DataGrid HorizontalAlignment="Left" Margin="148,10,0,0" VerticalAlignment="Top" Height="215" Width="707"
                      RenderOptions.ClearTypeHint="Enabled"
                      TextOptions.TextFormattingMode="Display"
                      SelectionUnit="FullRow"
                      IsSynchronizedWithCurrentItem="True"
                      DataContext="{Binding ElementName=cmbSelect, Path=SelectedItem}"
                      ItemsSource="{Binding XPath=./LanguageList/Language}"
                      AutoGenerateColumns="False" GridLinesVisibility="All"><DataGrid.Columns><DataGridTextColumn Header="Language Code"
                                        Binding="{Binding XPath=TargetCode}"/><DataGridTextColumn Header="Language Name"
                                        Binding="{Binding XPath=TargetLanguageName}"/><DataGridTextColumn x:name="dtcVendorName" Header="Vendor Name"
                                        Binding="{Binding XPath=VendorList/Vendor/Name}"/><DataGridTextColumn x:name="dtcVendorSurname" Header="Vendor Surname"
                                        Binding="{Binding XPath=VendorList/Vendor/Surname}"/><DataGridComboBoxColumn x:name="dcbVendorList" Header="Default Vendor"
                                            DisplayMemberPath="{Binding XPath=*}"/></DataGrid.Columns></DataGrid></Grid></UserControl>
  

I have a problem with binding DataGridComboBoxColumn "dcbVendorList" to list all vendors from an xml. Combobox should have a Surname displayed as an item.

Then based on the selection from a dcbVendorList, datagridtextcolumn "dtcVendorName" and "dtcVendorSurname" should be filled with data from this combobox.

I've tried to use Xpath * and . with no luck. It seems that a current item is "Language" xml node from a datacontext.

<DataGridComboBoxColumn x:name="dcbVendorList" Header="Default Vendor" DisplayMemberPath="{Binding XPath=*}


Any help is greatly appreciated.

changes in user control's view model to be triggered in Main page View model

$
0
0

Hi Everyone,

I have a Page(Main Page) which is using couple of user controls. The data context of Main page is from Main View Model.

Each user control has its respected view model.

I want changes in user control's view model to be triggered in Main page View model.

Please let me know how can this be achieved.

Thanks in advance,

Pooja Soni

TextBlock text partial binding

$
0
0

Hi all,

I want to implement that a TextBlock partial binding.

For example:

<TextBlock Text="This is a ***"
       VerticalAlignment="Center"
       Style="{DynamicResource BlockTitle}"/>
The cs file:
 public string DisplayName
        {
            get
            {
                return "Book";
            }
        }


Then I want to display "This is a Book" in UI,how can I do?

I don't want to set DisplayName="This is a Book".


Freezable cannot be frozen (only after user logs in remotely and then logs back locally)

$
0
0

Hi,

I get a 'This Freezable cannot be frozen' exception each time a user logs in remotely to the app and then logs in locally.

It is thrown as domain exception so no way to avoid the app crashing.

There are no Freeze() calls in our application so it must be something with the resources.

What can be causing it? Any ideas? I have read many articles on Freezables online but found no hints on how to solve this particular case.

Regards,

Tomasz

System.InvalidOperationException: This Freezable cannot be frozen. at System.Windows.Freezable.Freeze() at System.Windows.SystemResources.Freeze(Object resource) at System.Windows.SystemResources.FindDictionaryResource(Object key, Type typeKey, ResourceKey resourceKey, Boolean isTraceEnabled, Boolean allowDeferredResourceReference, Boolean mustReturnDeferredResourceReference, Boolean& canCache) at System.Windows.SystemResources.FindResourceInternal(Object key, Boolean allowDeferredResourceReference, Boolean mustReturnDeferredResourceReference) at System.Windows.FrameworkElement.FindResourceInternal(FrameworkElement fe, FrameworkContentElement fce, DependencyProperty dp, Object resourceKey, Object unlinkedParent, Boolean allowDeferredResourceReference, Boolean mustReturnDeferredResourceReference, DependencyObject boundaryElement, Boolean isImplicitStyleLookup, Object& source) at System.Windows.StyleHelper.GetChildValueHelper(UncommonField`1 dataField, ItemStructList`1& valueLookupList, DependencyProperty dp, DependencyObject container, FrameworkObject child, Int32 childIndex, Boolean styleLookup, EffectiveValueEntry& entry, ValueLookupType& sourceType, FrameworkElementFactory templateRoot) at System.Windows.StyleHelper.GetChildValue(UncommonField`1 dataField, DependencyObject container, Int32 childIndex, FrameworkObject child, DependencyProperty dp, FrugalStructList`1& childRecordFromChildIndex, EffectiveValueEntry& entry, ValueLookupType& sourceType, FrameworkElementFactory templateRoot) at System.Windows.StyleHelper.GetValueFromTemplatedParent(DependencyObject container, Int32 childIndex, FrameworkObject child, DependencyProperty dp, FrugalStructList`1& childRecordFromChildIndex, FrameworkElementFactory templateRoot, EffectiveValueEntry& entry) at System.Windows.FrameworkElement.GetValueFromTemplatedParent(DependencyProperty dp, EffectiveValueEntry& entry) at System.Windows.FrameworkElement.GetRawValue(DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry& entry) at System.Windows.FrameworkElement.EvaluateBaseValueCore(DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry& newEntry) at System.Windows.DependencyObject.EvaluateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry newEntry, OperationType operationType) at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType) at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp, Boolean preserveCurrentValue) at System.Windows.StyleHelper.InvalidateResourceDependentsForChild(DependencyObject container, DependencyObject child, Int32 childIndex, ResourcesChangeInfo info, FrameworkTemplate parentTemplate) at System.Windows.TreeWalkHelper.InvalidateStyleAndReferences(DependencyObject d, ResourcesChangeInfo info, Boolean containsTypeOfKey) at System.Windows.TreeWalkHelper.OnResourcesChanged(DependencyObject d, ResourcesChangeInfo info, Boolean raiseResourceChangedEvent) at System.Windows.TreeWalkHelper.OnResourcesChangedCallback(DependencyObject d, ResourcesChangeInfo info, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1._VisitNode(DependencyObject d, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.VisitNode(FrameworkElement fe, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.VisitNode(DependencyObject d, Boolean visitedViaVisualTree) at System.Windows.DescendentsWalker`1.WalkLogicalChildren(FrameworkElement feParent, FrameworkContentElement fceParent, IEnumerator logicalChildren) at System.Windows.DescendentsWalker`1.WalkFrameworkElementLogicalThenVisualChildren(FrameworkElement feParent, Boolean hasLogicalChildren) at System.Windows.DescendentsWalker`1.IterateChildren(DependencyObject d) at System.Windows.DescendentsWalker`1.StartWalk(DependencyObject startNode, Boolean skipStartNode) at System.Windows.TreeWalkHelper.InvalidateOnResourcesChange(FrameworkElement fe, FrameworkContentElement fce, ResourcesChangeInfo info) at System.Windows.SystemResources.InvalidateTreeResources(Object args) 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) 

xaml byte[] into compbobox

$
0
0

Hi to all,

I have a combobox with values from DataContext. the 1 field is byte[] values.

how can I show them in my combobox?

thanks in advance 

PubCB.DataContext= myDatatable

        <ComboBoxx:Name="PubCB"ItemsSource="{Binding Path=name}"Grid.Row="0"Grid.Column="1">
           
<ComboBox.ItemTemplate>
               
<DataTemplate>
                   
<TextBlockText= ??????               </DataTemplate>
           
</ComboBox.ItemTemplate>
       
</ComboBox>

How to alter the element without a name?

$
0
0

I have a UserControl, where I get the information of some elements using VisualTreeHelper class. But when I change the data and want to apply it to the same control (element), it doesn't update. Is there any way that I could update the xaml from the code behind? 

            Path arc1 = null,cap1 = null, cap2 = null;
            Path[] paths;

paths = FindVisualChildren<Path>(userC).ToArray(); arc1 = paths[0]; cap1 = paths[1]; cap2 = paths[2]; PathFigure pf = new PathFigure(); pf.StartPoint = new Point(0, h); pf.Segments.Add(new ArcSegment(new Point(w, h), size, 0, false, SweepDirection.Clockwise, true)); PathGeometry pg = new PathGeometry(); pg.Figures.Add(pf); arc1.Data = pg; //obvious it'll not update here because it just copied the information to another

// Path. But how can I update it?



How to have 2 MouseClick Events individually in wpf..?

$
0
0

HI,

 I have canvas in Xaml with MouseLeftButtonDown event for panning control, and path in Xaml.cs for Brush it randomly. Here Path is bounded between canvas ("CanvasPanel.Children.Add(path);"). Now when I use to move using MouseLeftButtonDown event, it is triggering both events of Path and Canvas. I want 2 events trigger differently so that when I use for panning it shouldn't fill color in Path which is bounded between Canvas. I Don't want to fill Path with color when I do Panning for canvas.

Here is the link for Source code:

https://onedrive.live.com/?cid=876cfae94c306176&id=876CFAE94C306176!106&ithint=file,rar&authkey=!AO5OFco268nDANg

Please Help me.

Thanks,

Viswa.




what's the best strategy of validating multiple user input?

$
0
0

currently I have an app that has a window where has multiple TextBoxes, CheckBox, etc., receiving user data input. but the user data requires to be validated. since what kind of data user is required to input is not certain, therefore i may have to add extra controls programmatically.

following is my brief demo:

<Window x:Class="WpfApplication7.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"><Grid><Label Content="Don't care" HorizontalAlignment="Left" Margin="10,12,0,0" VerticalAlignment="Top" Height="23" Width="78"/><TextBox HorizontalAlignment="Left" Height="23" Margin="93,16,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="414"/><Label Content="Important1*" HorizontalAlignment="Left" Margin="10,40,0,0" VerticalAlignment="Top" Height="23" Width="78"/><TextBox HorizontalAlignment="Left" Height="23" Margin="93,44,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="414"/><Label Content="Importtant2*" HorizontalAlignment="Left" Margin="10,68,0,0" VerticalAlignment="Top" Height="23" Width="78"/><TextBox HorizontalAlignment="Left" Height="23" Margin="93,72,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="414"/><Label Content="Reserved for Programmatically added." HorizontalAlignment="Left" Margin="10,96,0,0" VerticalAlignment="Top" Height="188" Width="497"/><Button Content="Submit" HorizontalAlignment="Left" Margin="432,0,0,10" VerticalAlignment="Bottom" Width="75"/></Grid></Window>

please notice that "Don't care" need not be validated in such case.

to valid each, i have implemented ValidationRule so that it will be done automatically. however, i need to know if all data is validated when user push the submit button, so that i can ensure user did a good job.(or maybe the button is disabled if not all user data is validated)

so my question is, is there any clean way for me to validate all the fields that is important for me(in such context, with* followed)? notice that, the programmatically added controls may be bound to important fields too.


Handle Double Click

$
0
0
I am currently listening to void OnMouseLeftButtonDown(MouseButtonEventArgs e). I want to handle clicks and double clicks in there. I wish to execute a custom logic lets called it logic1 per click and another different custom logic lets call it logic2 per double click. However it seems the method is being called twice when I double click. First time with ClickCount 1 and second time with the ClickCount 2. Therefore logic1 is always executed.

How to handle only double clicks without having logic1 executed again?

protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
  if (e.ClickCount > 1)
  {
   // logic2
  }
  else
  {
    // logic1
  }
}

WPF DataGrid.SelectedItem does not highlight when moved to last item in CollectionChanged event handler

$
0
0

I can't figure out what is going wrong for this corner case. Basically, I have a DataGrid that is bound to an ObservableCollection in my view model. The SelectedItem of the DataGrid is also bound to a property in my view model. I then have a command that executes a delete operation on the selected item. I have also added an event handler for CollectionChanged so that I can be notified when an item has been removed from collection. In that event handler I update the selected item property to the item at the same index (or previous index if it was the last item). I do this in the collection changed event handler because the collection gets updated from a variety of places and want the selection to be managed from this one place.

The problem is that when I select the second to last item and delete it, the selected item is updated to the last item (since that item was shifted down into that index). But the DataGrid highlighting is not updated to that row. If I turn row headers on, I can see the row header is highlighted, but the row is not. The highlighting works fine if I delete any other item in the list, including the last item.

I created a small app that reproduces this (excuse the sloppy MVVM as I threw this together for demo only).

XAML:

<DockPanel><Button DockPanel.Dock="Bottom" Content="Remove" Command="{Binding DeleteCommand}" CommandParameter="{Binding}"  /><DataGrid DockPanel.Dock="Top" ItemsSource="{Binding People}" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}"><DataGrid.RowStyle><Style><Style.Resources><!--Forces the selection color to be the system highlight color when the item does not have focus--><SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="{x:Static SystemColors.HighlightColor}" /></Style.Resources></Style></DataGrid.RowStyle></DataGrid></DockPanel>

ViewModel:

    public class ViewModel : INotifyPropertyChanged
	{
		public ViewModel()
		{
			People = new ObservableCollection<Person> { new Person("Jack"), new Person("Jill"), new Person("Jon"), new Person("Jane"), new Person("Joe") };
			People.CollectionChanged += PeopleOnCollectionChanged;
		}

		private ObservableCollection<Person> mPeople;
		public ObservableCollection<Person> People
		{
			get { return mPeople; }
			set
			{
				if (mPeople != value)
				{
					mPeople = value;
					OnPropertyChanged("People");
				}
			}
		}

		private Person mSelectedPerson;
		public Person SelectedPerson
		{
			get { return mSelectedPerson; }
			set
			{
				if (mSelectedPerson != value)
				{
					mSelectedPerson = value;
					OnPropertyChanged("SelectedPerson");
				}
			}
		}

		private DeleteCommand mDeleteCommand;
		public DeleteCommand DeleteCommand
		{
			get { return mDeleteCommand ?? (mDeleteCommand = new DeleteCommand()); }
		}

		private void PeopleOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			if (e.Action == NotifyCollectionChangedAction.Remove)
			{
				SelectedPerson = People.Count == 0 ? null : e.OldStartingIndex < People.Count ? People[e.OldStartingIndex] : People.Last();
			}
		}

		public event PropertyChangedEventHandler PropertyChanged;

		[NotifyPropertyChangedInvocator]
		protected virtual void OnPropertyChanged(string propertyName)
		{
			PropertyChangedEventHandler handler = PropertyChanged;
			if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
		}
	}


	public class Person
	{
		public string Name { get; set; }

		public Person(string name)
		{
			Name = name;
		}
	}

	public class DeleteCommand : ICommand
	{
		public void Execute(object parameter)
		{
			ViewModel viewModel = ((ViewModel) parameter);
			viewModel.People.Remove(viewModel.SelectedPerson);
		}

		public bool CanExecute(object parameter)
		{
			ViewModel viewModel = ((ViewModel)parameter);
			if (viewModel == null) return false;
			return viewModel.People.Count > 0 && viewModel.SelectedPerson != null;
		}

		public event EventHandler CanExecuteChanged
		{
			add { CommandManager.RequerySuggested += value; }
			remove { CommandManager.RequerySuggested -= value; }
		}
	}

Character spacing in TextBlock/TextElement

$
0
0
Is there a way to change the spacing between characters in a WPF text element?  Something like the CSS letter-spacing property?  Thanks!

Landscape documents in DocumentViewer

$
0
0

Hi.  I have a Windows Form application in VB 2013 with a Document Viewer control which I am using to display XPS documents. 

Most of the documents I want to display here are reports from a legacy system which were designed to be in landscape format  The XPS documents were created either by printing text reports to the XPS Document Writer printer or by printing PDF reports to the XPS Document Writer printer. In both cases the orientation was set to Landscape and I want to be able to display and print them this way. 

When they are displayed in the Document Viewer control, the text runs sideways.  I believe this is because the pages are oriented this way after "printing" them to XPS.  In other words, they are in landscape format, with the text running parallel to the long edge of the page, but the pages themselves are orientated in portrait.   I would like to be able to convert these documents into documents which have the pages themselves oriented in landscape.  I have tried a number of things, including a MatrixTransform, but have not been able to get this to work.

Does anyone have any suggestions/examples of how to do this? 

Thanks.Mary


Mary Leathem

Viewing all 18858 articles
Browse latest View live


Latest Images