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

Custom Control - Best place for visual-tree generation?

$
0
0

I'm building a custom control (extending Canvas) which should present a chartflow diagram (nodes and connectors). It will be feeded through databinding and a dependency property (ItemSource). The control will generate:

1. Node-items (based on ItemSource)
2. Connectors (lines) between each and every node
3. An adornerlayer on most of the nodes

Should I generate this visual/logical -tree inside my ItemSourceUpdated -eventhandler? In the overrided ArrangeOverride method? Or whats best practice?




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?

  

Black window remains open even after closing the window programatically

$
0
0
I have an application which has multiple windows. From mainwindow button click event I am closing the child form of the application. The child window is opened after a successful socket, serial or gateway connection attempt, after which the application do work with some threads and while clicking on a button on mainwindow I am closing this child window after disconnecting the respective connection mode. But after the close event the child window background gets black and it remains open unless and until I just do a minimize and maximize the application. Please help me on this to get this issue fixed.

Texbox handle convert problem

$
0
0

Hi,

I'm trying to create a validate form but when i put no int value in textbox bind on int i get the ardorner with the error about fail conversion.

But i can valid a form.

In my little app, just put empty value in Qty and press add.

My code didn't detect a problem on quantity...

Can i catch a problem to don't add the line ?

here for exemple : http://www.filedropper.com/validationexample_4

creating generic user control

$
0
0
I have a generic structure called POSet<T> which I would like to create some user controls e.g. POSetGraph<T> : UserControl.  How do I do this?

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!

Just in case any one needs a Observable Collection that deals with large data sets, and supports FULL EDITING...

$
0
0

the VirtualizingObservableCollection does the following:

  • Implements the same interfaces and methods as ObservableCollection<T> so you can use it anywhere you’d use an ObservableCollection<T> – no need to change any of your existing controls.
  • Supports true multi-user read/write without resets (maximizing performance for large-scale concurrency scenarios).
  • Manages memory on its own so it never runs out of memory, no matter how large the data set is (especially important for mobile devices).
  • Natively works asynchronously – great for slow network connections and occasionally-connected models.
  • Works great out of the box, but is flexible and extendable enough to customize for your needs.
  • Has a data access performance curve so good it’s just as fast as the regular ObservableCollection – the cost of using it is negligible.
  • Works in any .NET project because it’s implemented in a Portable Code Library (PCL).

The latest package can be found on nugget. Install-Package VirtualizingObservableCollection. The source is on github. 


How to check if xps document is blank or has values in c# WPF

$
0
0

Can anyone suggest me the solution for this?

I check it using FileSize but it did not work.

Thanks,


NumericUpDown control in wpf

$
0
0
 Cound find NumericUpDown control in WPF. Is there any dll needs to be added?

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. 

Change Row and Add new row on Datagrid using MVVM

$
0
0

Below is my Xaml and ViewModel class looks like. I try to change the existing row or add new row but both of them doesnt work. When I click empty row, it looses the focus. how I can achieve it directly on Xaml or in ViewModel without using code behind?

<UserControl x:Class="ucCustomer"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:myWPF="clr-namespace:myWPF"
         xmlns:vm="clr-namespace:myWPF.ViewModels"
         mc:Ignorable="d"
       MinWidth="750" MinHeight="650" ><Grid><Grid.DataContext><vm:CustomerVM /></Grid.DataContext><Button x:Name="btnSave" Margin="0,10,10,0" Width="120" Height="25" Content="Save Changes" Command="{Binding btnClick}" HorizontalAlignment="Right" VerticalAlignment="Top"/><DataGrid x:Name="grdData"  AutoGenerateColumns="False" Margin="10,50,10,5"   Style="{StaticResource myDataGrid}"
                  ItemsSource="{Binding Customers, Mode=TwoWay}"><DataGrid.Columns><DataGridTextColumn Header="CustomerId"    Binding="{Binding Path=CustomerId}" Width="50"></DataGridTextColumn><DataGridTextColumn Header="CustomerName" Binding="{Binding Path=CustomerName}" Width="150"></DataGridTextColumn><DataGridTextColumn Header="AccountId"  Binding="{Binding Path=AccountId}" Width="130"></DataGridTextColumn><DataGridTextColumn Header="AccountName"   Binding="{Binding Path=AccountName}" Width="200"></DataGridTextColumn><DataGridTextColumn Header="ModifyDate" IsReadOnly="True"  Binding="{Binding Path=ModifyDate}" Width="130"></DataGridTextColumn></DataGrid.Columns></DataGrid></Grid>

   Namespace ViewModels
            Public Class CustomerVM
                Inherits BaseViewModel
                Implements ICustomerVM

                Private _Customer

    s As New ObservableCollection(Of Models.Customer)
            Private mySaveCommand As ICommand
            Private myLoadCommand As ICommand

            Public Sub New()
                mySaveCommand = New Commands.SaveCustomers(Me)
                myLoadCommand = New Commands.LoadCustomer()
                _Customers = GetCustomers()
            End Sub


            Public Property Customers() As ObservableCollection(Of Models.Customer)
                Get
                    Return _Customers
                End Get
                Set(value As ObservableCollection(Of Models.Customer))
                    _Customers = value
                End Set
            End Property

            Public ReadOnly Property btnClick() As ICommand
                Get
                    Return mySaveCommand
                End Get
            End Property



            Function GetCustomers() As ObservableCollection(Of Models.Customer) Implements ICustomerVM.GetCustomer


                If _Customers Is Nothing OrElse _Customers.Count = 0 Then myLoadCommand.Execute(_Customers)

                Return _Customers
            End Function


            Public Function SaveCustomerstoDB() As Integer
                Dim myContext As New Models.myModelContext
                Return myContext.SaveChanges()
            End Function


        End Class
    End Namespace


    Namespace ViewModels
    Public Class BaseViewModel
        Implements INotifyPropertyChanged

        Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
        Protected Sub OnPropertyChanged(propertyName As String)
            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
        End Sub

        Protected Sub SetAndNotify(Of T)(ByRef field As T, value As T, propertyName As String)
            If Not EqualityComparer(Of T).[Default].Equals(field, value) Then
                field = value
                OnPropertyChanged(propertyName)
            End If
        End Sub

    End Class
End Namespace


"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

Why does this raise a Parse exception in XAML?

$
0
0

I suppose I am a beginner in C#, and I'm decently familiar with creating basic Windows forms projects. However, when it comes to XAML and using WPF, I'm just a tick above clueless. In the Form constructor of a windows forms app, the following for loop would not throw an exception.

 for (int i = 0; i < Game_Moderator.Return_Combo_Box_Items().Length; i++)
            {
                Card_Selection.Items.Add(Game_Moderator.Return_Combo_Box_Items()[i]);
            }

However, in XAML's  MainWindow() method, I receive the following exception: 

"A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll. Additional information: 'The invocation of the constructor on type 'Go_Fish_WPF.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'."

Yet, when I add each item individually via the add method:

Card_Selection.Items.Add("Ace");

Card_Selection.Items.Add("Two");

...

Card_Selection.Items.Add("King");

There are no exceptions. Why does the for loop cause an Exception? By the way, Card_Selection is a combobox.

Also, Game_Moderator.Return_Combo_Box_Items() is perfectly functional.



Get selected Listbox item

$
0
0

hi,

Can someone tell me  how to know which listboxitem from a listbox was selected by the user?

This is the listboxitem.

<ListBoxItem HorizontalAlignment="Left" Name="Canvas" Foreground="White"  FontSize="60" Background="White" BorderBrush="White" Width="763" Height="72"  >

The following are not working

 if (MyList.SelectedItem.ToString() == "Canvas")
            {
                canvaswindow cw = new canvaswindow();
                cw.Show();
                this.Close();
            }


 private void ListBoxItem_Selected_1(object sender, RoutedEventArgs e)
        {
            if (MyList.SelectedItem.ToString() == "Canvas")
            {
                canvaswindow cw = new canvaswindow();
                cw.Show();
                this.Close();
            }
        }

Thanks,

Shaleen


TheHexLord

Wpf background for button disappeared on mouseover - cannot override the style

$
0
0

I have a button in wpf with a background image
I try to override the style to avoid picture disapeared onmouseover.

i try to do this here:

<Window x:Class="WPFTEst.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"
        xmlns:my="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"><Window.Resources><ControlTemplate x:Key="TemplateTest" TargetType="ButtonBase"><my:ButtonChrome Background="{TemplateBinding Control.Background}"
                             BorderBrush="{TemplateBinding Control.BorderBrush}"
                             Name="Chrome" RenderDefaulted="{TemplateBinding Button.IsDefaulted}" RenderMouseOver="{TemplateBinding UIElement.IsMouseOver}" RenderPressed="{TemplateBinding ButtonBase.IsPressed}" SnapsToDevicePixels="True"><ContentPresenter Content="{TemplateBinding ContentControl.Content}"
                                  ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}"
                                  ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"
                                  HorizontalAlignment="{TemplateBinding Control.HorizontalContentAlignment}"
                                  Margin="{TemplateBinding Control.Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding Control.VerticalContentAlignment}" /></my:ButtonChrome><ControlTemplate.Triggers><Trigger Property="ToggleButton.IsMouseOver" Value="True"><Setter Property="Background" TargetName="Chrome" Value="{Binding Path=Background, RelativeSource={RelativeSource}}" /></Trigger><Trigger Property="ToggleButton.IsChecked" Value="True"><Setter Property="my:ButtonChrome.RenderPressed" TargetName="Chrome" Value="True" /></Trigger><Trigger Property="UIElement.IsEnabled" Value="False"><Setter Property="Control.Foreground" Value="#FFADADAD" /></Trigger></ControlTemplate.Triggers></ControlTemplate></Window.Resources><Grid><Button Content="Button" Height="128" HorizontalAlignment="Left" Margin="130,88,0,0" Name="button1" VerticalAlignment="Top" Width="272" Template="{StaticResource TemplateTest}"><Button.Background><ImageBrush ImageSource="/WPFTEst;component/Images/Tulips.jpg" /></Button.Background><Button.BorderBrush><ImageBrush ImageSource="/WPFTEst;component/Images/Tulips.jpg" /></Button.BorderBrush></Button></Grid></Window>

where is the mouseover trigger ?

i took the template from base template "extract value to resource"

thanks.

How to set the background in a listview?

$
0
0

I would like to set the background of the ítems in a listview to transparent because I will set the background with a converter.

I am doing this with datagrids and works, and the way tha I am using is:

<DataGrid Name="myDatagrid"
	Style="{StaticResource DataGridCustomBackground}"><DataGrid.RowStyle><Style TargetType="DataGridRow"><Setter Property="Background"><Setter.Value><MultiBinding Converter="{StaticResource myDataGridBackgroundMultivalueConverter}"><MultiBinding.Bindings><Binding /><Binding RelativeSource="{RelativeSource Self}" Path="IsSelected"/></MultiBinding.Bindings></MultiBinding></Setter.Value></Setter></Style></DataGrid.RowStyle></Datagrid>


And I have a resourcedictionary:

<Style TargetType="{x:Type DataGrid}" x:Key="DataGridCustomBackground"><Setter Property="IsReadOnly" Value="true"/><Setter Property="CanUserAddRows" Value="false"/><Setter Property="CanUserDeleteRows" Value="true"/><Setter Property="AutoGenerateColumns" Value="false"/><Setter Property="VerticalScrollBarVisibility" Value="Visible"/><Setter Property="HorizontalScrollBarVisibility" Value="Visible"/><Setter Property="CanUserSortColumns" Value="true"/><Style.Resources><SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/><SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/><SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent"/><SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="Black"/></Style.Resources></Style>

The idea is to set transparent the default system colors to avoid to hide the background that I set in the converter.

I am trying to do the same with a listview, but it does not work. I do this:

<ListView Name"MyListView"
	Style="{StaticResource ListViewCustomBackground}"><ListView.ItemContainerStyle><Style TargetType="ListBoxItem"><Setter Property="Background"><Setter.Value><MultiBinding Converter="{StaticResource myListBoxItemsBackgroundMultivalueConverter}"><MultiBinding.Bindings><Binding /><Binding ElementName="ucPrincipal" Path="DataContext.MyProperty1"/><Binding ElementName="ucPrincipal" Path="DataContext.MyProperty2"/></MultiBinding.Bindings></MultiBinding></Setter.Value></Setter></Style></ListView.ItemContainerStyle></listView>

And the resource:

<Style TargetType="{x:Type ListViewItem}" x:Key="ListViewItemCustomBackground"><Style.Resources><SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/><SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black"/><SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent"/><SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}" Color="Black"/></Style.Resources></Style>

But in this case, the backgroud is hidden, I need to deselect the ítem to see the background that I set. The background is set correctly, but is hidden.

Thank so much.


Why does not return the correct color?

$
0
0

I have a resources dictionary with a color:

<SolidColorBrush x:Key="MyColorWhenSelected" Color="{Binding Source={x:Static SystemColors.HighlightBrush}}"/>

I have added this resources to App.Current.Resources.MergedDictionaries.

Later, in my converter to set the background in a listview, I return:

return App.Current.Resources["MyColorWhenSelected"]

But the item has a white color, is not blue like the defult selected color.

However, if I return:

return System.Windows.SystemColors.HighlightBrush

Then the color is the expected one.

I have tried another color from my dictionary, por example:

<SolidColorBrush x:Key="TestColor" Color="White" />

If I return

return App.Current.Resources["MyColorWhenSelected"]

this works as expected.

I guess that the problem is because in this second case all is SolidColorBrush type, while in the first case one is SolidColorBrush and the other is SystemColors.

My idea is to use the resource dictionary because if in the future I decide to change the highlight color, change it in this resource, and not to change in all the converters in which I use this color.

Thank so much.

Full Customize AvalonDock

$
0
0
Hello

I try to customize AvalonDock in my WPF application. I have some problem and I need your help and possible sample code.
1- I would like to add content (with command), for example "Import", "Save" .. when right clicking on each TabItem
2-Have full control when a tab floating: Change the title, increase the font size, change the context menu and especially display a scroll when resizing.
3- Being able to change the content of a tab (User Control) from a parent control (MainWindow).
Thanks for your help

IsModified (IsDirty) flag management

$
0
0

Hello,

My question is about IsModified (IsDirty) flag management technique.

I have a SDI application, and I wish to implement modification detection as good as possible. I'm sure WPF offer all what I need, but I'm just too recent in the practice to make it correctly.

I have a datacontext object (model) that contains objects, that contains objects... classic. I need to change the flag to true each time an information is modified by the user.

I'm sure putting boolean in each objects of the model, with INotifyPropertyChange or some Tracking interface is a stupid thing.

I'm sure creating a view-model over each object of the datacontext is a bad approach too, because cost in memory, tons of work to "wrap" models, and assume coherency.

What could be the approach. To be concrete, the application has a TreeView at left, that make possible to select, add or remove an item, and there's a formular at the right to change properties of items and add remove change sub-objects in a data-grid.

I really need to progress on that topic.

Kind regards.

UPDATE single ROW from DATAGRID without refreshing the entire ItemsSource

$
0
0

Hello there,

   I have a simple datagrid that has an ItemsSource of ObjectQuery<DbDataRecord>.

   Let's say I want to refresh a single row from the datagrid, (Because a specific item i know has been changed) without refreshing the entire ItemsSource because the source query is quite big.

Any ideas?

Thanks.


-- Jorge_M_P

How to: subscribe for the viewer's Error event

$
0
0

I am running a third party report tool and am trying to understand how to comply with their request. My report works fine in all export modes with the exception of export to word at which time it throws a "Index was outside the bounds of the array" error. This does not occur in any other export mode (i.e., Excel, RTF, TIFF, yada, yada.)

The request from the vendor is " subscribe for the viewer's Error event and the report's Error event to get the exception."

I run Win8.1 and would like to create a subscription to the View Event log to trap the occurrence of this error. I have tried to locate some documentation online as to how I can accomplish this.

Where can I find this information as well as an example?


Tom Mann MCSD C#

Viewing all 18858 articles
Browse latest View live


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