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

Auto-generated code in WPF shows error. (C#, WPF, Visual Studio Community 2013)

$
0
0

Recently i have started playing with C# in Visual Studio 2013 Community. I was creating a simple data binding while i encountered following error. What i was doing i was using drag-n-drop fr om my database to main window. Visual studio generated required XAML and .cs file. There was following error present with the code. I searched a lot and didn't found a solution. It was showing on 

Error: "an object reference is required to access non-static field method or property"

following is my XAML.

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:rrplproj" x:Class="rrplproj.MainWindow" Title="MainWindow" Height="700" Width="1024" WindowState="Maximized" Loaded="Window_Loaded"><Window.Resources><local:rDataSet x:Key="rDataSet"/><CollectionViewSource x:Key="dateViewSource" Source="{Binding Date, Source={StaticResource rDataSet}}"/><CollectionViewSource x:Key="deliveryViewSource" Source="{Binding Delivery,

Source={StaticResource rDataSet}}"/></Window.Resources>

<Grid Background="#FFDBFDF8"><Grid.ColumnDefinitions><ColumnDefinition Width="165*"/><ColumnDefinition Width="172*"/><ColumnDefinition Width="171*"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="56*"/><RowDefinition Height="149*"/><RowDefinition Height="18*"/></Grid.RowDefinitions><Grid x:Name="grid1" DataContext="{StaticResource dateViewSource}" HorizontalAlignment="Left"

Margin="19,23,0,0" Grid.Row="1" VerticalAlignment="Top" Height="32" Width="151"><Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="Auto"/></Grid.RowDefinitions><Label Content="Date:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0"

VerticalAlignment="Center"/><DatePicker x:Name="dateDatePicker" Grid.Column="1" HorizontalAlignment="Left" Margin="3" Grid.Row="0"

SelectedDate="{Binding Date, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"

VerticalAlignment="Center"/></Grid><Grid x:Name="grid2" Grid.Column="1" DataContext="{StaticResource deliveryViewSource}"

HorizontalAlignment="Left" Margin="64,18,0,0" Grid.Row="1" VerticalAlignment="Top"><Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="Auto"/></Grid.RowDefinitions><Label Content="Truck No:" Grid.Column="0" HorizontalAlignment="Left" Margin="3" Grid.Row="0"

VerticalAlignment="Center"/><TextBox x:Name="truckNoTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="23" Margin="3"

Grid.Row="0" Text="{Binding TruckNo, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}"

VerticalAlignment="Center" Width="120"/></Grid></Grid>

and following is auto generated code by ide in C#.

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace rrplproj { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { // Load data into the table Date. You can modify this code as needed. rrplproj.rDataSetTableAdapters.DateTableAdapter rDataSetDateTableAdapter =

new rrplproj.rDataSetTableAdapters.DateTableAdapter(); rDataSetDateTableAdapter.Fill(rDataSet.Date); System.Windows.Data.CollectionViewSource dateViewSource =

((System.Windows.Data.CollectionViewSource)(this.FindResource("dateViewSource"))); dateViewSource.View.MoveCurrentToFirst(); // Load data into the table Delivery. You can modify this code as needed. rrplproj.rDataSetTableAdapters.DeliveryTableAdapter rDataSetDeliveryTableAdapter =

new rrplproj.rDataSetTableAdapters.DeliveryTableAdapter(); rDataSetDeliveryTableAdapter.Fill(rDataSet.Delivery); System.Windows.Data.CollectionViewSource deliveryViewSource =

((System.Windows.Data.CollectionViewSource)(this.FindResource("deliveryViewSource"))); deliveryViewSource.View.MoveCurrentToFirst(); } } }


The error is shown here:

rDataSetDateTableAdapter.Fill(rDataSet.Date);

and here:

 rDataSetDeliveryTableAdapter.Fill(rDataSet.Delivery);
it is showing red line under 
(rDataSet.Date)
and 
(rDataSet.Delivery)

Your help is appreciated. 

Thank you for reading till the last line.


XamlWriter skips “x:Name” attribute while saving ResourceDictionary

$
0
0

Here's custom style:

<Style TargetType="{x:Type Button}"><Setter Property="Focusable" Value="false" /><Setter Property="Background" Value="{StaticResource AppBackBrush}"/><Setter Property="Foreground" Value="{StaticResource AppBrush}"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button"><Border BorderBrush="{StaticResource AppBrush}"
                            Name="content"
                            BorderThickness="1"
                            CornerRadius="3"
                            Background="{StaticResource AppBackBrush}"><Grid Background="Transparent"><Label Content="{TemplateBinding Content}"
                                   HorizontalContentAlignment="Center"
                                   VerticalContentAlignment="Center"
                                   Grid.Row="0" Grid.Column="0"
                                   Background="Transparent"
                                   Style="{x:Null}"
                                   Foreground="{TemplateBinding Foreground}"
                                   Padding="{TemplateBinding Padding}"/></Grid><Border.RenderTransform><!-- push the content a bit to the left and the top --><TranslateTransform x:Name="translation"
                                                X="-1" Y="-1"/></Border.RenderTransform></Border><ControlTemplate.Triggers><Trigger Property="IsPressed" Value="True"><Trigger.EnterActions><BeginStoryboard><Storyboard><DoubleAnimation Duration="0:0:0"
                                                         To="0"
                                                         Storyboard.TargetName="translation"
                                                         Storyboard.TargetProperty="(TranslateTransform.X)"/><DoubleAnimation Duration="0:0:0"
                                                         To="0"
                                                         Storyboard.TargetName="translation"
                                                         Storyboard.TargetProperty="(TranslateTransform.Y)"/></Storyboard></BeginStoryboard></Trigger.EnterActions><Trigger.ExitActions><BeginStoryboard><Storyboard><DoubleAnimation Duration="0:0:0"
                                                         To="-1"
                                                         Storyboard.TargetName="translation"
                                                         Storyboard.TargetProperty="(TranslateTransform.X)"/><DoubleAnimation Duration="0:0:0"
                                                         To="-1"
                                                         Storyboard.TargetName="translation"
                                                         Storyboard.TargetProperty="(TranslateTransform.Y)"/></Storyboard></BeginStoryboard></Trigger.ExitActions></Trigger><Trigger Property="IsEnabled" Value="False"><Setter TargetName="content" Property="Opacity" Value="0.5" /></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>

I save this ResourceDictionary that contains this style to string like this:

    XamlWriter.Save(s);

where s is ResourceDictionary. The problem is that when I get expected string, it looks so:

<Style TargetType=\"Button\" x:Key=\"{x:Type Button}\"><Style.Resources><ResourceDictionary /></Style.Resources><Setter Property=\"UIElement.Focusable\"><Setter.Value><s:Boolean>False</s:Boolean></Setter.Value></Setter><Setter Property=\"Panel.Background\"><Setter.Value><SolidColorBrush>#FFF1F2F4</SolidColorBrush></Setter.Value></Setter><Setter Property=\"TextElement.Foreground\"><Setter.Value><SolidColorBrush>#FF13776A</SolidColorBrush></Setter.Value></Setter><Setter Property=\"Control.Template\"><Setter.Value><ControlTemplate TargetType=\"Button\"><Border BorderThickness=\"1,1,1,1\" CornerRadius=\"3,3,3,3\" BorderBrush=\"#FF13776A\" Background=\"#FFF1F2F4\" Name=\"content\"><Border.RenderTransform><TranslateTransform X=\"-1\" Y=\"-1\" /></Border.RenderTransform><Grid><Grid.Style><Style TargetType=\"Grid\"><Style.Resources><ResourceDictionary /></Style.Resources><Setter Property=\"Panel.Background\"><Setter.Value><SolidColorBrush>#00FFFFFF</SolidColorBrush></Setter.Value></Setter></Style></Grid.Style><Label Content=\"{TemplateBinding ContentControl.Content}\" Background=\"#00FFFFFF\" Foreground=\"{TemplateBinding TextElement.Foreground}\" HorizontalContentAlignment=\"Center\" VerticalContentAlignment=\"Center\" Padding=\"{TemplateBinding Control.Padding}\" Style=\"{x:Null}\" Grid.Column=\"0\" Grid.Row=\"0\" /></Grid></Border><ControlTemplate.Triggers><Trigger Property=\"ButtonBase.IsPressed\"><Trigger.EnterActions><BeginStoryboard><Storyboard><Storyboard.Children><DoubleAnimation To=\"0\" Duration=\"00:00:00\" Storyboard.TargetName=\"translation\" Storyboard.TargetProperty=\"(TranslateTransform.X)\" /><DoubleAnimation To=\"0\" Duration=\"00:00:00\" Storyboard.TargetName=\"translation\" Storyboard.TargetProperty=\"(TranslateTransform.Y)\" /></Storyboard.Children></Storyboard></BeginStoryboard></Trigger.EnterActions><Trigger.ExitActions><BeginStoryboard><Storyboard><Storyboard.Children><DoubleAnimation To=\"-1\" Duration=\"00:00:00\" Storyboard.TargetName=\"translation\" Storyboard.TargetProperty=\"(TranslateTransform.X)\" /><DoubleAnimation To=\"-1\" Duration=\"00:00:00\" Storyboard.TargetName=\"translation\" Storyboard.TargetProperty=\"(TranslateTransform.Y)\" /></Storyboard.Children></Storyboard></BeginStoryboard></Trigger.ExitActions><Trigger.Value><s:Boolean>True</s:Boolean></Trigger.Value></Trigger><Trigger Property=\"UIElement.IsEnabled\"><Setter Property=\"UIElement.Opacity\" TargetName=\"content\"><Setter.Value><s:Double>0.5</s:Double></Setter.Value></Setter><Trigger.Value><s:Boolean>False</s:Boolean></Trigger.Value></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>

Please take a look at TranslateTransform in Border.RenderTransform. In the ResourceDictionary it has x:Name="translation", but the name is missing in the output string. 

Where was I mistaken or is this a bug? Thanks in advance.



Window design view gives:"NullReferenceException: Object reference not set to an instance of an object." but exectution of code works

$
0
0

Using Visual Studio 2013, C# and WPF.

I have a simple User Control when used in a window causes: "NullReferenceException: Object reference not set to an instance of an object."

However when code is executed it works as expected.

   at Slakt004.UCDateFlat.DateType_SelectionChanged(Object sender, SelectionChangedEventArgs e)
   at System.Windows.Controls.SelectionChangedEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
   at System.Windows.Controls.ComboBox.OnSelectionChanged(SelectionChangedEventArgs e)
   at System.Windows.Controls.Primitives.Selector.InvokeSelectionChanged(List`1 unselectedInfos, List`1 selectedInfos)
   at System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
   at System.Windows.Controls.Primitives.Selector.SelectionChanger.SelectJustThisItem(ItemInfo info, Boolean assumeInItemsCollection)
   at System.Windows.Controls.Primitives.Selector.OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   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.CoerceValue(DependencyProperty dp)
   at System.Windows.Controls.Primitives.Selector.OnItemsChanged(NotifyCollectionChangedEventArgs e)
   at System.Windows.Controls.ItemsControl.OnItemCollectionChanged2(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Collections.Specialized.NotifyCollectionChangedEventHandler.Invoke(Object sender, NotifyCollectionChangedEventArgs e)
   at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
   at System.Windows.Controls.ItemCollection.OnViewCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
   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.Specialized.CollectionChangedEventManager.OnCollectionChanged(Object sender, NotifyCollectionChangedEventArgs args)
   at System.Windows.Data.CollectionView.OnCollectionChanged(NotifyCollectionChangedEventArgs args)
   at System.Windows.Data.ListCollectionView.RefreshOverride()
   at System.Windows.Data.CollectionView.RefreshInternal()
   at System.Windows.Data.CollectionView.Refresh()
   at System.Windows.Data.CollectionView.EndDefer()
   at System.Windows.Data.CollectionView.DeferHelper.Dispose()
   at System.Windows.Controls.ItemCollection.SetCollectionView(CollectionView view)
   at System.Windows.Controls.ItemCollection.SetItemsSource(IEnumerable value, Func`2 GetSourceItem)
   at System.Windows.Controls.ItemsControl.OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   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.Data.BindingExpressionBase.Invalidate(Boolean isASubPropertyChange)
   at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
   at System.Windows.Data.BindingExpression.Activate(Object item)
   at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
   at System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Run(Object arg)
   at MS.Internal.Data.DataBindEngine.OnLayoutUpdated(Object sender, EventArgs e)
   at System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()
   at System.Windows.ContextLayoutManager.UpdateLayout()
   at System.Windows.UIElement.UpdateLayout()

Slakt004.UCDateFlat.DateType_SelectionChanged(Object sender, SelectionChangedEventArgs e) looks as follows:

        private void DateType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DateType.Width = 35;

            if (DateType.SelectedItem != null)
            {
                DateTypeDef selectedDateType = DateType.SelectedItem as DateTypeDef;

                source.DateType = selectedDateType.Id;

                //If changed to "between" no update should be done here of if year = 0 or when toYear is to small
                //the event will be created when toYear is updated
                if (selectedDateType.Id != Enumerations.between)
                {
                    //Generate an event
                    UCDateUpdateEventArgs args = new UCDateUpdateEventArgs(source);
                    UCDateUpdated(this, args);
                }
                else
                {
                    if (source.YearTo >= source.Year)
                    {
                        //Generate an event
                        UCDateUpdateEventArgs args = new UCDateUpdateEventArgs(source);
                        UCDateUpdated(this, args);

                    }
                }

            }

        }

If I comment out the event triggers then Visual Studio is able to show the design view of the window.

None of the tips I have found when searching has helped. Any tips are welcome!

How to generate WPF Xaml through XSD (xml schema definition)

$
0
0

Hi Experts

I am working on Projects where we need to generate wpf ui (xaml) at runtime as per different requirements. We are trying to generate xaml from xsd file. We are able to generate UI from xml but as size of xml can be large we are reluctant to use xml as xaml generation source. I am attaching a sample image what we are trying to do

UI elements Description

For each complex node in xsd, we need a panel which can have add or delete button depending on minoccurs and maxoccurs of the node. Inside panel we want to add different ui elements.

Please suggest if there is any way to do this or any one have worked in this direction?

Thanks

Praveen

How do I gracefully handle XamlParseExceptions?

$
0
0

If a control that is dynamically loaded as part of a template has an error, it causes a XamlParseException which crashes the entire application.

I can hook into the Application.DispatcherUnhandledException event, but setting Handled to true on the DispatcherUnhandledExceptionEventArgs argument does not disable the problematic control. As a result, WPF tries again to apply the template, causing the error to be thrown once more, resulting in an infinite loop.

Is there any way to disable the problematic control so that it stops trying to render?

Here is how to reproduce this scenario:

1. Create a WPF application.

2. Add a Window called "Dialog1" and a UserControl called "UserControl1".

3. Add the following code to each file (namespaces and root XAML elements left out):

App.xaml.cs:

(Also add the following namespace reference to the top: using System.Windows.Threading;)

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        DispatcherUnhandledException += OnDispatcherUnhandledException;
    }

    private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
    {
        e.Handled = true;
    }
}

Dialog1.xaml:

(Also add the following namespace reference: xmlns:local="clr-namespace:your app namespace")

<StackPanel><Button Content="Cause XamlParseException" Click="Button_Click" /><ListBox ItemsSource="{Binding Mode=OneWay}"><ListBox.ItemTemplate><DataTemplate><local:UserControl1 /></DataTemplate></ListBox.ItemTemplate></ListBox></StackPanel>

Dialog1.xaml.cs:

public partial class Dialog1 : Window
{
    public Dialog1()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var list = new object[1];
        list[0] = new object();

        DataContext = list;
    }
}

MainWindow.xaml:

<StackPanel><Button Content="Show Dialog" Click="Button_Click" /></StackPanel>

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        var dlg = new Dialog1();
        dlg.ShowDialog();
    }
}

UserControl1.xaml.cs:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();

        throw new Exception();
    }
}

Run the solution, click the "Show Dialog" button, and then click the "Cause XamlParseException" button. This will cause the exception to be thrown repeatedly.

Importing the correct Namespace into XAML: How hard could it be? :)

$
0
0

The documentation for How to: Import a Namespace into XAML, XAML Namespaces and Namespace Mapping and XmlnsDefinitionAttribute is anemic.

  • It doesn't cover a known issue with namespaces in .NET versions <= 4. Please see Microsoft Connect Issue: Reference aliases are ignored on some xaml files.
  • Nowhere does the documentation explain how to specify in the Xmlns value which assembly to load if two assemblies share the same name.

I want to break down the expected behavior for XAML under the following namespace shadowing scenarios:

  1. Two assemblies with the same name, with the same namespaces, loaded in the same AppDomain, with the same XmlnsDefinitionAttribute mappings.
  2. Two assemblies with the same name, with the same namespaces, loaded in the same AppDomain, with different XmlnsDefinitionAttribute mappings.
  3. Two assemblies with different names, with the same namespaces, loaded in the same AppDomain, with the same XmlnsDefinitionAttribute mappings.
  4. Two assemblies with different names, with the same namespaces, loaded in the same AppDomain, with different XmlnsDefinitionAttribute mappings.

What's the expected behavior in all of these shadowing scenarios?

In addition, I want to call out one scenario specifically that the above 4 cases are intended to address: What is the XAML equivalent to theextern alias C# keyword?  Currently, the only approach I can think of is to extend FooBar in a separate C# class as FooBarExt and use C# to handle the details.  However, this doesn't address the following problem:

  • Two assemblies with different names, with the same namespaces, loaded in the same AppDomain, with the same XmlnsDefinitionAttribute mappings.

Under the following scenario:

  • FooBar has a ControlTemplate and references an embedded resource ResourceDictionary in its assembly as the default Look & Feel for the control (generic.xaml), and that ResourceDictionary uses XmlnsDefinitionAttributes that are identical across assembly versions, regardless of how the assemblies are named.

Finally, is there some hook somewhere to override a vendor's XmlnsDefinitionAttribute if they do something non-deterministic like Test Cases 1 or 3 above?

The valid business scenario we are addressing is loading two versions of a GridControl in the same composite application.  Since it is a composite application, different groups within an organization migrate to the latest version at different times, as they all have different release schedules in-line with management objectives.  The control is (silently) failing when it tries to load the ControlTemplate, because it is loading the XAML resource from the "older" version of the assembly.  In this scenario, the assemblies are named differently (e.g. Grid.v1.0.dll and Grid.v2.0.dll).

In addition, to be exhaustive, I would like to cover some further test cases:

  • The same as above, except find and replace "with the same namespaces" with "with disjoint namespaces".
  • The same as above, except find and replace "with the same namespaces" with "with namepaces that have a non-empty intersection and a non-empty symmetric difference".
  • Using different AppDomains
  • Typical namespace shadowing tests, such as accessibility modifiers (x:ClassModifier andx:FieldModifier), which can change the public interface of a module. e.g. What happens if a private interface becomes protected?  If a protected interface becomes internal?  If internal becomes public?  And the opposite direction.  Will XAML then bind to the namespace that is visible?
  • Applying every test involving XmlnsDefinitionAttribute to XmlnsPrefixAttribute as well, to ensure namespace collisions don't happen when serializing to XAML.
  • Using assembly aliases to specify which assembly to load when two or more assemblies share the same name

Other real world examples:

WPF VB.NET : how to insert a notepad in listbox

$
0
0

I already used the code as below.

 Dim openfile1 = New Microsoft.Win32.OpenFileDialog With {.Filter = "Text (*.Text)|*.txt"}
        If (openfile1.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
            For Each line As String In File.ReadAllLines(openfile1.FileName)
                ListBox1.Items.Add(line)
            Next
        End If

This code serves on windows form, when I use in WPF there are no errors but can not display the contents of the notepad on the listbox. there is no other solution


thanks to Magnus

I did not think his mistake on System.Windows.Forms.DialogResult
thank you very much, the code works.

How do i split a line in a csv file and populate a combobox and a textbox with the parts

$
0
0

What I'm trying to do is split the line and fill a combobox and with the selecteditem and the textbox with the value of the combobox selecteditem which is the second part of the line split.

Thanks in advance for the help or suggestions.


How to get cursor position in XAML template?

$
0
0

I made a template for a button and I want to get the location of the cursor relative to the button when Iclick it and setting the text of the button with the location I get ("X=..., Y=...") or storing the values somehow, but I can't use anycs code because I am in a ResourceDictionary. How am I supposed to do this?

Please, help me!

How to import MySql database to windows phone 8.1 app

$
0
0

Hello everyone I'm Designing a new windows phone 8.1 app and I need some help from you.

I have a database that Im using for the some app but for Windows.

currently using db4free.net

and use this code

  Mysqlconn = New MySqlConnection
        Mysqlconn.ConnectionString = "server=db4free.net;Port=3306; user id=%%%%%; password=%%%%%%%; database=%%%%%%%%"
        Dim READER As MySqlDataReader

        Try
            Mysqlconn.Open()
            Dim Query As String
            Query = "SELECT * FROM Manager WHERE Name='" & TextBox1.Text & "' AND Password='" & TextBox2.Text & " ' "
            Command = New MySqlCommand(Query, Mysqlconn)
            READER = Command.ExecuteReader
            Dim count As Integer
            count = 0
            While READER.Read
                count = count + 1
            End While
            If count = 1 Then
                MsgBox("Mire se vini'" & TextBox1.Text & "'")
                FORMAKRYESORE.Show()
                Me.Close()

            ElseIf count > 1 Then
                MsgBox("Mire se vini'" & TextBox1.Text & "'")
            Else
                MsgBox("Manager'" & TextBox1.Text & "' is not in the data")
            End If

            Mysqlconn.Close()

        Catch ex As MySqlException
            MsgBox(ex.Message)
        Finally
            Mysqlconn.Dispose()

        End Try

this is the code that  I use to login.  but on windows phone cant import Mysql connector. not sure why... any suggestion how to deal with this?

or should I use SQLite? I dont know nothing about the code on SQLite...

Renaming the binding and the property?: C#

$
0
0

How can I rename a property: eg,

        private string _Material;

        public string Material
        {
            get { return _Material; }
            set
            {
                _Material = value;
                NotifyPropertyChanged();
            }
        }

And it would rename its binding in xaml: eg,

<TextBox Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2" Text="{Binding Path=Material}" TextChanged="materialTB_TextChanged"  />

Lets say from Material to Mat. 

Why in MVVM, we shouldn't use the partial class of the View as the View-Model?

$
0
0

Maybe it's a very naive question. But I cannot imagine at this moment in time the reason why we should not use the partial class of the View as the VM. It could be because I haven't yet face a situation where it'd make any difference or haven't realized. 

Or 

What are advantages and disadvantages of doing so?

  

Debugger exception on WPF loading

$
0
0

Hello,

    I am looking for a little help with this.  I have a WPF browser form that I am trying to load.  I run the debugger, but when it gets to the page I get the following:

An exception of type 'System.Security.SecurityException' occurred in System.Data.dll but was not handled in user code

Additional information: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

If there is a handler for this exception, the program may be safely continued.

The call stack for that shows this:

> HomeInventoryWebForms.exe!HomeInventoryWebForms.frmMoviesAdd.dgMTVAddFormat_Window_Loaded(object sender, System.Windows.RoutedEventArgs e) Line 70 C#

So here is the code behind the form:

public frmMoviesAdd()
            {
            InitializeComponent();
            this.Loaded += dgMTVAddFormat_Window_Loaded;
            this.Loaded += dgMTVAddGenre_Window_Loaded;
            }
private void dgMTVAddFormat_Window_Loaded(object sender, RoutedEventArgs e)
            {
            FormatDataClassesDataContext data = new FormatDataClassesDataContext();
            List<tblFormat> Format = (from FormatName in data.tblFormats select FormatName).ToList();
            dgMTVAddFormat.ItemsSource = Format;
            }

This is backed up with LINQ to SQL class that was auto generated:

	[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="HomeInventory")]
	public partial class FormatDataClassesDataContext : System.Data.Linq.DataContext
	{

		private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();

    #region Extensibility Method Definitions
    partial void OnCreated();
    partial void InserttblFormat(tblFormat instance);
    partial void UpdatetblFormat(tblFormat instance);
    partial void DeletetblFormat(tblFormat instance);
    #endregion

		public FormatDataClassesDataContext() :
				base(global::HomeInventoryWebForms.Properties.Settings.Default.HomeInventoryConnectionString, mappingSource)
		{
			OnCreated();
		}

		public FormatDataClassesDataContext(string connection) :
				base(connection, mappingSource)
		{
			OnCreated();
		}

		public FormatDataClassesDataContext(System.Data.IDbConnection connection) :
				base(connection, mappingSource)
		{
			OnCreated();
		}

		public FormatDataClassesDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
				base(connection, mappingSource)
		{
			OnCreated();
		}

		public FormatDataClassesDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
				base(connection, mappingSource)
		{
			OnCreated();
		}

		public System.Data.Linq.Table<tblFormat> tblFormats
		{
			get
			{
				return this.GetTable<tblFormat>();
			}
		}
	}

	[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.tblFormat")]
	public partial class tblFormat : INotifyPropertyChanging, INotifyPropertyChanged
	{

		private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);

		private int _FormatID;

		private string _FormatName;

    #region Extensibility Method Definitions
    partial void OnLoaded();
    partial void OnValidate(System.Data.Linq.ChangeAction action);
    partial void OnCreated();
    partial void OnFormatIDChanging(int value);
    partial void OnFormatIDChanged();
    partial void OnFormatNameChanging(string value);
    partial void OnFormatNameChanged();
    #endregion

		public tblFormat()
		{
			OnCreated();
		}

		[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_FormatID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
		public int FormatID
		{
			get
			{
				return this._FormatID;
			}
			set
			{
				if ((this._FormatID != value))
				{
					this.OnFormatIDChanging(value);
					this.SendPropertyChanging();
					this._FormatID = value;
					this.SendPropertyChanged("FormatID");
					this.OnFormatIDChanged();
				}
			}
		}

		[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_FormatName", DbType="VarChar(MAX) NOT NULL", CanBeNull=false)]
		public string FormatName
		{
			get
			{
				return this._FormatName;
			}
			set
			{
				if ((this._FormatName != value))
				{
					this.OnFormatNameChanging(value);
					this.SendPropertyChanging();
					this._FormatName = value;
					this.SendPropertyChanged("FormatName");
					this.OnFormatNameChanged();
				}
			}
		}

		public event PropertyChangingEventHandler PropertyChanging;

		public event PropertyChangedEventHandler PropertyChanged;

		protected virtual void SendPropertyChanging()
		{
			if ((this.PropertyChanging != null))
			{
				this.PropertyChanging(this, emptyChangingEventArgs);
			}
		}

		protected virtual void SendPropertyChanged(String propertyName)
		{
			if ((this.PropertyChanged != null))
			{
				this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}
	}
}
#pragma warning restore 1591

Now I am trying to bind this all to a checked box datagrid in the WPF with code that looks like this:

<Label x:Name="lblMTVAddFormat" Style="{StaticResource Label Style}" Content="Formats" Margin="335,74,0,0" Width="97"/><DataGrid x:Name="dgMTVAddFormat" Margin="437,74,10,265" AutoGenerateColumns="False"><DataGrid.Columns><DataGridCheckBoxColumn Binding="{Binding fBool}" /><DataGridTextColumn Binding="{Binding Path='FormatName'}" /></DataGrid.Columns></DataGrid>
This is all running from a local disk, connected to a remote developer database.  I have no build errors or anything when I go to the debug, hitting continue sends it to another break for the exact same reason.  Which loops out of the program and shuts down the debugger.  Could anyone point me in the direction to go since it is throwing this error on debug? 


Michael R. Mastro II

Combobox Focus(),Color

$
0
0
           if (cBoxislem.Text.Trim() == string.Empty)
            {
                booValue = false;
                cBoxislem.Focusable = true;
                cBoxislem.Focus();
                cBoxislem.Background = NullColorFromHexa(255, 14, 14);
                return booValue;
            }

and;

       public SolidColorBrush NullColorFromHexa(byte R,byte G ,byte B )
        {
           SolidColorBrush color = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, R, G, B));
           return color;
        }
value is empty when I change the color of the background;

Deploying a WPF app

$
0
0

hi,

I developed a wpf app and I am trying to deploy it. 

I created the setup using installshield special edition.

i have listed .net framework as a prerequisite and it is included in the setup files.

Still everytime i try to install my app, it directly installs the app and not the .net framework.



Pls help.

Thanks,

Shaleen


TheHexLord


Updating a Label content from code behind using dispatcher

$
0
0

hi,

I am trying to update a label's content from code behind.

This part of the code is running in background worker. I wrote the following code to update a label's content:

volumecontrol.Dispatcher.BeginInvoke(new Action(() =>
                        {
                            volumecontrol.Content = volumeupdate;
                        }));

 i tried using both BeginInvoke and Invoke but the application exits with the error:

System.InvalidOperationException' occurred in WindowsBase.dll

Using Invoke works when updating the UI from another thread but it not working in this case:

Pls help.

Thanks,

Shaleen


TheHexLord

DoDragDrop oddity with Right Mouse Button

$
0
0

Hi all,

More experimentation - today with Drag & Drop.

Everything seems fine when performing this with the left mouse button, but when initiating this from WPF
with the right mouse button it appears to trigger the PreviewDrop event on the originating object.

I've tried intercepting QueryContinueDragHandler, which is fired and is having an Action set of Continue - all to no avail.

Much time with google shows no examples of people using the right mouse button with DoDragDrop, and a single query on this forum in September with someone having a similar problem.  No replies to that thread - hopeing for more luck today!

So, has anyone successfully initiated a system based Drag/Drop using the right mouse button?  In this case I'm working with a ListView, but I suspect that is fairly irrelevant.

Events occuring with Right Mouse Button depressed (and dragging a small way) are:
Call to: System.Windows.DragDrop.DoDragDrop

Callback: DropSource_ContinueDragEventHandler
Callback: DropTarget_PreviewDragEnter
Callback: DropSource_ContinueDragEventHandler
Callback: DropTarget_PreviewDrop


With the Left Mouse Button:
Call to: System.Windows.DragDrop.DoDragDrop

Callback: DropSource_ContinueDragEventHandler
Callback: DropTarget_PreviewDragEnter
Callback: DropSource_ContinueDragEventHandler
Callback: DropSource_ContinueDragEventHandler
Callback: DropSource_ContinueDragEventHandler
etc...


Anyone aware of any issues in this area?

Thanks,

Glyn

PS: The behaviour is different if dragging something from another application / desktop to a drop target, so it appears to be related to the originating side of things. ie, there is no problem when dragging an object from the desktop or similar.

Image processing with decode pixels for TIFF

$
0
0

I have a major issue in my applicaiton due to this issue, Could have been in the base framework for decoding TIF issue.

DECODE PIXEL HEIGHT/WIDTH

"The JPEG and Portable Network Graphics (PNG) codecs natively decode the image to the specified size; other codecs decode the image at its original size and scale the image to the desired size."

in order to display thumbnail in Listbox wrappanel, Image source is been generated with Decodepixels.

This is working neat for JPEGS, where as for TIF it sucks, takes ages for loading.

XAML:

<ListBox Name="scannedimages"  Background="Gray"  SelectionMode="Multiple" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="1" ItemsSource="{Binding }" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel IsItemsHost="True" Orientation="Horizontal"  ></WrapPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding Path=ImageSource}"></Image>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Class with ImageSource property, setting the property on binding the path in delegate

private void  setvalues()
        {
           if(FullPath!=null)
           {
               //if (System.IO.Path.GetExtension(FullPath.ToString()).ToUpper() == ".TIF")
               //{

               //    Stream tiff = new System.IO.FileStream(FullPath.ToString(), FileMode.Open, FileAccess.Read, FileShare.Read);
               //    TiffBitmapDecoder tiffdec = new TiffBitmapDecoder(tiff, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnLoad);
               //    BitmapSource bs = tiffdec.Frames[0];
               //    ImageSource = bs;

                   //JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                   //MemoryStream memoryStream = new MemoryStream();
                   //BitmapImage bImg = new BitmapImage();

               //    encoder.Frames.Add(BitmapFrame.Create(bs));
               //    encoder.Save(memoryStream);

               //    bImg.BeginInit();
               //    bImg.DecodePixelWidth = 100;
               //    bImg.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
               //    bImg.CacheOption = BitmapCacheOption.OnLoad;
               //    bImg.StreamSource = new MemoryStream(memoryStream.ToArray());
               //    bImg.EndInit();

               //    memoryStream.Close();

               //    ImageSource = bImg;
               //    //int width = 100;
               //    //int height = 120;
               //    //var target = new TransformedBitmap( bs,new ScaleTransform(width / bs.Width * 96 / bs.DpiX, height / bs.Height * 96 / bs.DpiY, 0, 0));
               //    //var thumbnail = BitmapFrame.Create(target);
               //    //if (thumbnail.CanFreeze)
               //    //    thumbnail.Freeze();
               //    //return thumbnail;    
               //    //GdPictureImaging img = new GdPictureImaging();
               //    //int imgaid = img.CreateGdPictureImageFromFile(FullPath.ToString());
               //    //int thumbnail = img.CreateThumbnailHQ(imgaid, 100, 120);
               //    //BitmapImage bi = new BitmapImage();
               //    //using (MemoryStream strea = new MemoryStream())
               //    //{
               //    //    img.SaveAsStream(thumbnail, strea, DocumentFormat.DocumentFormatTIFF, 4);
               //    //    strea.Position = 0;
               //    //    bi.BeginInit();
               //    //    bi.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
               //    //    bi.CacheOption = BitmapCacheOption.OnLoad;
               //    //    bi.UriSource = null;
               //    //    bi.StreamSource = strea;
               //    //    bi.EndInit();
               //    //}
               //    //img.ReleaseGdPictureImage(imgaid);
               //    //img.ReleaseGdPictureImage(thumbnail);
               //    //ImageSource = bi;
               //}
               //else
               //{
                   BitmapImage bi = new BitmapImage();
                   bi.BeginInit();
                   bi.DecodePixelWidth = 200;                 
                   bi.CacheOption = BitmapCacheOption.OnDemand;
                   bi.CreateOptions = BitmapCreateOptions.DelayCreation;
                   bi.UriSource = new Uri(FullPath.ToString());
                   bi.EndInit();
                   ImageSource= bi;                  
               //}
           }

        }

CODE BEHIND:

 String folderPath = txtPath.Text.Trim();
            if (Directory.Exists(folderPath))
            {
                DirectoryInfo dirinfo = new DirectoryInfo(folderPath);
                scannedimages.DataContext = pages;
                Task.Run(() =>
                   {
                       foreach (var file in dirinfo.EnumerateFiles())
                       {
                           if (file.Extension.ToUpper().Equals(".TIF") || file.Extension.ToUpper().Equals(".JPG"))
                           {
                               Dispatcher.Invoke((Action)(() =>
                               {
                                   pages.Add(new ImageItem(file.FullName, file.Name));
                               }), DispatcherPriority.Background);

                           }
                       }
                   });
            }

- I have also used URItoBitmap converter for direct binding in XAML code

- You notice- I have used different approaches nothing is working as fast as JPEGs loading. appreciate your help.


Wiring up an event handler in the XAML editor

$
0
0
How to wire up an event handler in the XAML ceditor?

It's time for the TechNet Wiki WPF "Great Guru Love-in"! You too can get some loving!

$
0
0

February at TechNet Wiki usually involves a lot of love...

 

We love to read.

We love to learn.

We love our gurus, for they love to give.

 

Computer Geek Love Story Stock Photos

 

We love to make friends and promote great content.

We love to meet the community, and get closer to you.

  

 

We love to interview our winners, and bestow much love and honor upon them.

We love to tell the world of your achievements, and we promote those most active to inner circles!

All you have to do is add an article to TechNet Wiki from your own specialist field. Something that fits into one of the categories listed on the submissions page. Copy in your own blog posts, a forum solution, a white paper, or just something you had to solve for your own day's work today.

Drop us some nifty knowledge, or superb snippets, and become MICROSOFT TECHNOLOGY GURU OF THE MONTH!

This is an official Microsoft TechNet recognition, where people such as yourselves can truly get noticed!

HOW TO WIN

1) Please copy over your Microsoft technical solutions and revelations toTechNet Wiki.

2) Add a link to it on THIS WIKI COMPETITION PAGE (so we know you've contributed)

3) Every month, we will highlight your contributions, and select a "Guru of the Month" in each technology.

If you win, we will sing your praises in blogs and forums, similar to the weekly contributor awards. Once "on our radar" and making your mark, you will probably be interviewed for your greatness, and maybe eventually even invited into other inner TechNet/MSDN circles!

Winning this award in your favoured technology will help us learn the active members in each community.

Feel free to ask any questions below.

More about TechNet Guru Awards

Thanks in advance!
Pete Laker


#PEJL
Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over toTechNet Wiki, for future generations to benefit from! You'll never get archived again, and you could win weekly awards!

Have you got what it takes o become this month's TechNet Technical Guru? Join a long list of well known community big hitters, show your knowledge and prowess in your favoured technologies!



#PEJL
Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over toTechNet Wiki, for future generations to benefit from! You'll never get archived again, and you could win weekly awards!

Have you got what it takes o become this month's TechNet Technical Guru? Join a long list of well known community big hitters, show your knowledge and prowess in your favoured technologies!

Viewing all 18858 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>