WPF problem in visual studio generated file g.vb “Namespace or type..

 

This warning was in the Visual Studio generated file. Warning is:

Namespace or type specified in the Imports ‘SRS.WpfControlLibrary1’ doesn’t contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn’t use any aliases. …SRS.WPF.Controls\obj\Debug\ucDataDrivenDGButton.g.vb 15 9 SRS.WPF.Controls

I had renamed the project and the Assembly name and the root namespace.

I did a search for the “SRS.WpfControlLibrary1” and found some required fixes/changes. Although I do not remember its creation this project used a Themes\Generic.xaml with an incorrect namespace, so I changed that.

The Generic.xaml seems to be special and in the AssemblyInfo.vb there was an attribute

<Assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)>

I also cleaned and built the project after the Generic.xaml update and now all ok

 

Similar Error

With VB Project Namespace change the .g.vb file references the old namespace.

Solution

The xaml had

xmlns:my1=”clr-namespace: … old namespace

Updated this and saved (possibly build also) and the project and the problem went away

 

End.

 

Advertisements

WPF datagrid takes a long time to load

Scenario

myDataGrid is in a simple WPF Grid control where a RowDefinition has a Height=”*”

<Grid >
   <Grid.RowDefinitions>
   <RowDefinition Height=”*” />
</Grid.RowDefinitions>

And if myDataTable has a large row count then the following may ‘hang’ or take a long time to load on following code:

myDataGrid.ItemsSource = myDataTable.DefaultView

The issue is that if the DataGrid is in a control that has unlimited height then it will render the whole DataGrid.

 

Solution

Options to resolve this include:

  1. Changing the RowDefinition Height
  2. Add MaxHeight to the DataGrid, so <DataGrid x:Name=”myDataGrid” MaxHeight=”1000″ />

Performance is then fine.

With thanks to: http://stackoverflow.com/questions/3336921/unreasonable-wpf-datagrid-loading-time

End.

WPF List Box

ItemTemplate – DataTemplate

            <ListBox ItemsSource="{Binding}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <StackPanel Orientation="Horizontal">
                                <StackPanel.Resources>
                                    <Style TargetType="TextBlock">
                                        <Setter Property="Margin" Value="0, 0, 5, 0" />
                                    </Style>
                                </StackPanel.Resources>
                                <TextBlock Text="{Binding Path=ID}" />
                                <TextBlock Text="{Binding Path=Task1}" />
                                <TextBlock Text="{Binding Path=PercentComplete}" />
                            </StackPanel>
                            <TextBlock Text="Resource names here" Margin="50, 0, 0, 0" />
                            <!--<TextBlock Text="{Binding Path=ResourceName}" Margin="50, 0, 0, 0" />-->
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

Sorting

        xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"

        <CollectionViewSource x:Key="taskViewSource" d:DesignSource="{d:DesignInstance my:Task, CreateList=True}">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="CompleteFlag"
                                     Direction="Descending" />
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>

 

Style DataTrigger

            <ListBox ItemsSource="{Binding}">
                <ListBox.Resources>
                    <Style TargetType="{x:Type ListBoxItem}">
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=CompleteFlag}"
                                         Value="True">
                                <Setter Property="Background"
                                        Value="Yellow" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </ListBox.Resources>
...
            </ListBox>

WPF DataGrid Get Current Row

Data Grid – Get Current Row. E.g. For Jump to Details – Data Grid Button Click

<DataGrid.Columns>
<DataGridTemplateColumn Header="Details" Width="80">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button x:Name="JumpButtonColumn" Content="{Binding Path=AdviceNoteNo}" Click="JumpButtonColumn_Click"></Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>>

And the Code

private void JumpButtonColumn_Click(object sender, RoutedEventArgs e)
{
if (invoiceDataGrid.CurrentColumn != null && invoiceDataGrid.CurrentColumn.DisplayIndex == 0)
{
Invoice myInvoice = ((FrameworkElement)sender).DataContext as Invoice;
Jump(myInvoice.InvoiceNo);
}
};

or

Private Sub JumpButtonColumn_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
   If AdviceNoteDataGrid.CurrentColumn IsNot Nothing AndAlso AdviceNoteDataGrid.CurrentColumn.DisplayIndex = 0 Then
       Dim myAdviceNote As AdviceNote = CType((CType(sender, FrameworkElement)).DataContext, AdviceNote)
       Jump(myAdviceNote.AdviceNoteNo)
   End If
End Sub

End

WPF EntityFramework DataGrid ComboBox

There may be several ways of doing this:

    <UserControl.Resources>
        <CollectionViewSource x:Key="originatorViewSource" d:DesignSource="{d:DesignInstance my:Originator, CreateList=True}" />
        <CollectionViewSource x:Key="customerLookup" />
    </UserControl.Resources>
                    <DataGridComboBoxColumn x:Name="cboCustomer"
                                            Width="200"
                                            Header="Customer"
                                            ItemsSource="{Binding Source={StaticResource customerLookup}}"
                                            SelectedValueBinding="{Binding Path=CustomerID}"
                                            SelectedValuePath="ID"
                                            DisplayMemberPath="Customer1">
                    </DataGridComboBoxColumn>

        private void LoadComboBox()
        {
            try
            {
                SalesContext contextCustomer = new SalesContext();
                var customerList = from c in contextCustomer.Customers
                                   orderby c.Customer1
                                   select new { ID = c.ID, Customer1 = c.Customer1 };

                CollectionViewSource CustomerViewSource = (CollectionViewSource)this.Resources["customerLookup"];
                CustomerViewSource.Source = customerList.ToList();
                //cboCustomer.ItemsSource = customerList.ToList();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

 

End

WPF Quick Reminders

Windows Forms Integration

Dim myControl1 = New WpfControlLibrary.CustomControl1
 myControl1.Content = "Hello World"
Me.ElementHost1.Child = myControl1

Docking

You may want HorizontalAlignment or VerticalAlignment = “Stretch”

DataBinding

Imports System.Data.Entity

private AccountTypeContext _context = new AccountTypeContext();
private CollectionViewSource myCollectionViewSource;
//Next in Loaded. If in user control then:
// Do not load your data at design time.
if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
{ }
 myCollectionViewSource = (CollectionViewSource)this.Resources["accountTypeViewSource"];
_context.AccountTypes.Load();
myCollectionViewSource.Source = _context.AccountTypes.Local;

DataBinding – BindingNavigator Functions

        private void MoveFirstButton_Click(object sender, RoutedEventArgs e)
        {
            myCollectionViewSource.View.MoveCurrentToFirst();
        }
        private void MovePreviousButton_Click(object sender, RoutedEventArgs e)
        {
            myCollectionViewSource.View.MoveCurrentToPrevious();
        }
        private void MoveNextButton_Click(object sender, RoutedEventArgs e)
        {
            myCollectionViewSource.View.MoveCurrentToNext();
        }
        private void MoveLastButton_Click(object sender, RoutedEventArgs e)
        {
            myCollectionViewSource.View.MoveCurrentToLast();
        }
//


It may be necessary to use
myDataGrid.ScrollIntoView(myDataGrid.SelectedItem);

 

DataBinding – Filter

With acknowledgment to:

http://www.chateau-logic.com/content/wpf-entity-framework-listbox-datagrid-filtering-using-collectionviewsource-collectionview

and

http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.WINDOWS.DATA.COLLECTIONVIEWSOURCE.FILTER);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true

In _Loaded

       myCollectionViewSource.Filter += new FilterEventHandler(FilterTextBoxLike);
In Code - assuming you have a text box called FilterTextBox
        #region Filter
        bool FilterClearing;
        private void FilterTextBox_TextChanged(object sender, TextChangedEventArgs e)        {
            try             {
                if (FilterClearing == false)                    {
                        RefreshList();                    }
            }
            catch (Exception ex)            {
                MessageBox.Show(ex.Message);    
            }
        }

        private void RefreshList()
        {
            myCollectionViewSource.View.Refresh();
        }

        private void FilterTextBoxLike(object sender, FilterEventArgs e)
        {
            AccountType at = e.Item as AccountType;

            if (at.AccountType1.ToLower().Contains(FilterTextBox.Text.ToLower()))
            {
                e.Accepted = true;
            }
            else
            {
                e.Accepted = false;
            }
        }

        private void ClearFilterButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
		FilterClearing = true;
               FilterTextBox.Text = "";
		RefreshList();
            }
            catch (Exception ex)
            {
		MessageBox.Show(ex.Message);                
            }
            FilterClearing = false;
        }

        #endregion

.

Data Grid – Styles

 

DatePicker as UK style date

Two actions seem to be required

Imports System.Globalization
Imports System.Threading

Namespace My

Partial Friend Class MyApplication

Private Sub MyApplication_Startup(sender As Object, e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
Dim ci = New CultureInfo(Thread.CurrentThread.CurrentCulture.Name)
ci.DateTimeFormat.ShortDatePattern = “dd-MMM-yyyy”
Thread.CurrentThread.CurrentCulture = ci
End Sub

End Class

End Namespace

<DatePicker Name=”DateReportedTextBox” Text=”{Binding Path=DateReported, StringFormat={}{0:dd-MMM-yyyy}}” />


End

WPF freezes when dragging data source onto a Page or Window

Problem

WPF freezes when dragging data source onto a Page or Window

Possible Solution

Inspect datasource and see if it has a child table underneath it. Does this child expand to show the parent table again. If so then you may be creating an infinite loop when dragging the datasource onto the Page or Window

WPF Filter

Terrible trouble. Predicate confusion. Following works

Method 1 : Entity Framework

See http://wp.me/p17IS4-mX

Method 2

CType(BookViewSource.View, BindingListCollectionView).CustomFilter = String.Concat(“Title LIKE ‘%”, FilterTextBox.Text, “%'”)

Method 3

Dim view As New System.Data.DataView(Me.dsBook1.Books)
view.RowFilter = String.Format(“Title LIKE ‘%{0}%'”, FilterTextBox.Text)
MainGrid.DataContext = view

then possibly with Try-Catch

Private Sub ClearFilter()
MainGrid.DataContext = BookViewSource
CType(BookViewSource.View, BindingListCollectionView).CustomFilter = Nothing
End Sub

WPF RichTextBox: How To Load, Edit and Save Rich Text Format

See Ged Mead

http://vbcity.com/blogs/xtab/archive/2010/03/01/wpf-richtextbox-how-to-load-edit-and-save-rich-text-format.aspx

WPF RichTextBox : How to Load and Save Plain Text Content

See Ged Mead

http://vbcity.com/blogs/xtab/archive/2010/02/22/wpf-richtextbox-how-to-load-and-save-plain-text-content.aspx