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

Updating WPF Datagrid on changing ItemsSource

$
0
0

I currently have some XAML defined like this:

... ItemsSource="{Binding BomHeaders, NotifyOnSourceUpdated=True}">

AND this  _vm = new ViewModels.BomHeaderVM();

AND thisthis.DataContext = _vm;

If I retrieve some data like this BomHeaders = new ObservableCollection<Model.BoMHeader>(dal.GetBomHeader()); my data access layer return a list of entity framework POCO's.

My UI datagrid refreshes accordingly and I can add,remove objects.

My Question is if I clear my observable collection

and use a button to retrieve an entire new observable collection again like this

BomHeaders = new ObservableCollection<Model.BoMHeader>(dal.GetBomHeader());

How do I get the itemssource to refresh when I basically recreate the observable collection?

If I raise a PropertyChange event and in the event do this

 BindingOperations.GetBindingExpressionBase(this.test, DevExpress.Xpf.Grid.GridControl.ItemsSourceProperty).UpdateTarget();

The data is refreshed.

Is this the only way to do this?

Or is there some better way to do this declaratively in XAML?

Thanks


nlm


How can I set a gridviewcolumn to have TextWrap = Wrap when the column is bound at runtime?

$
0
0

I am binding a blank WPF gridview object to columns in a table at runtime using C# Binding and GridViewColumnobjects to manipulate the gridview. I need one type of column to have TextWrapping turned on, and I cannot seem to find the right method. 

System.Windows.Controls.GridViewColumn gvc;
System.Windows.Data.Binding binding;
gView.Columns.Clear();
                foreach (DataColumn column in dt.Columns)
                {
                    gvc = new System.Windows.Controls.GridViewColumn();
                    binding = new System.Windows.Data.Binding();
                    binding.Path = new PropertyPath(column.ColumnName);
                    binding.Mode = BindingMode.OneWay;
                    gvc.Header = column.Caption;
                    switch (column.ColumnName)
                    {
                        case "Unit":
                            gvc.Width = 60;
                            break;
                        case "Message":
                            gvc.Width = 600;
                            break;
                        case "Notes":
                            gvc.Width = 700;
                            //--THIS IS WHERE IS WANT TO SET gvc.TextWrapping="Wrap";

                            break;

                    }
                    gvc.DisplayMemberBinding = binding;
                    gView.Columns.Add(gvc);

}

How to show lots of data at the same time in WPF

$
0
0

Hi all,

We are converting an MDI based application to WPF. I have read many posts on the subject.  The most common are to use 1 of the codeplex solutions or find a 3rd party library.  Ok, that's fine if I want to stay with MDI.

The next most commong response is to use a tabbed page.  This is great until you have lots of data.

Imagine a typeical user of a big system with many tables. They often have to have multiple records from the same table open at a time, especially when dealing with data for other tables. In an MDI world, they just have all the forms open and can jump to them as needed (sort of like what we do in windows.)  A tabbed page approach might allow them to have all the forms open, but only 1 would ever be visible....

Think of a stock advisor on the phone with a client, having details of each stock they discuss open in individual windows, a customer page so they can take notes, and various forms up used to search for a variety of investments (with each type of investments having a different lookup and result approach.) 

What is the standard solution for complex situations like this in WPF?

Thanks


me (and yes, I DO mark correct answers)

A user control with 2 controls that autosize?

$
0
0

Hi,

I am new to WPF, but have been using Winforms for a while. 

In my winforms app, I have user controls (used extensively) that contain both a label and a data entry class (textbox, combobox, etc.)  The color of the label indicates if the data is required, valid, etc.  So there is a close coupling between them (hence the user control to contain them.)  Also, the label may be set to the left, right, or above the data control.  When it's to the left, I need to size the data control to fill the remaining space available.  When it's to the right, I need to calculate the size of the data element based on the width of the user control less the label width & offset.  You get the idea.  This is very easy in Winforms. 

I am trying to do the same in WPF.  But it seems to be much more difficult to do this using the approach I used above.  So I am sure I am doing it wrong.

Could someone point me in the right direction? 

I have been scouring my C# books and while they are quite infomative about all the other things I am doing wrong, I haven't yet found a clue about how to create a similar control. I tried Binging for an answer, but am clearly not able to figure out the correct search key words.

Any and all help is appreciated!

Thanks


me (and yes, I DO mark correct answers)

How to Change TreeViewItem color when cut

$
0
0

Hallo,

I have the below treeview. I use a hierarchical datatemplate. I am add commands like cope and paste for the treeviewitems. Im trying to change the color

of the treeviewitem's background when it i cut it and its not pasted yet. I cant find the way. Can someone shed some light on this?

<UserControl x:Class="SemcaUI.TreeViewControl"
             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:l="clr-namespace:myProject"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"><UserControl.Resources><HierarchicalDataTemplate DataType="{x:Type l:ColFirstCollection}" ItemsSource="{Binding Path=SecondCollection}"><DockPanel Height="15" IsEnabled="False"><Image Source="/MainWindowUI/Images/Cut.png"/><TextBlock Text="{Binding Path=FCName}"/></DockPanel></HierarchicalDataTemplate><HierarchicalDataTemplate DataType="{x:Type l:ColSecondCollection}" ItemsSource="{Binding Path=SecondCollection}"><DockPanel Height="15" IsEnabled="False"><Image Source="/MainWindowUI/Images/Cut.png"/><TextBlock Text="{Binding Path=SCName}"/></DockPanel></HierarchicalDataTemplate></UserControl.Resources><Grid><TreeView  x:Name="myTreeView" AllowDrop="True" TreeViewItem.Selected="myTreeView_Selected" ><TreeView.ItemContainerStyle><Style TargetType="{x:Type TreeViewItem}"><EventSetter Event="TreeViewItem.MouseRightButtonUp" Handler="myTreeView_MouseRightButtonUp"/><EventSetter Event="TreeViewItem.MouseMove" Handler="treeViewItem_MouseMove"/></Style></TreeView.ItemContainerStyle></TreeView></Grid></UserControl>


Jc

Getting scale factor

$
0
0
Guys, is there a way to find out what the current scale factor  or magnification? I'm talking about the one you can set in Control Panel\Appearance and Personalization\Display with values 100%, 125% and 150%.

wpf popup Dispay on the Chart

$
0
0
Has to define a chart control in the other panels show there is no problem, but can not be displayed in the popup. seeking what are the solutions

Operation is not valid while ItemCollection has no inner collection.

$
0
0

I got a user control 'SubForm'

When click a button on the main form, the 'SubForm' will be added and default data will load to the grid

SubForm subform = new SubForm(); grid_SubForm.Children.Add(subform);
subform.Visibility = Visibility.Visible;
subform.LoadDataToGrid();

Then I got error in LoadDataGrid()

This is function in 'SubForm' to load data in Data Grid as default

dataGrid_grid1's source and header information is set dynamically on User Control Loaded function.

     (subform.dataGrid_grid1.Items[row] as DataRowView).Row[column] = 1;

'Operation is not valid while ItemCollection has no inner collection. ItemCollection is uninitialized or binding on ItemsControl.ItemSource supplied null for collection.'

Any solution? thanks.




custom MultiDataTrigger support for Grid and StackPanel?

$
0
0

Hello,

i need to use DataTriggers in a lot of pages, that have also be edited by customers in a simple way. 

In default Control Triggers i can only use EventTriggers. I dont want to use DataTemplate on every place, to get MuliDataTriggers or DataTRiggers working.

Do you have any idea  how i can make StackPanel and Grid to have MultiDataTriggers?

Thank you a lot.

Best regards,

Simon


tu es, oder lass es

Navigating to pages within the app

$
0
0

Hi,

I want to navigate between pages within my WPF application in C#, but I am not sure if I am using the correct way.

Currently I am using this:

 
private void Register_Click(object sender, RoutedEventArgs e)
        {
            Register Register = new Register();
            Register.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            Register.Show();
            this.Close();
        }

I seen a example of using Method NavigationService.Navigate from this link.

private void TestPage_Click(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigate(new Uri("TestPage.xaml", UriKind.Relative));
        }

But I am getting this error:

Error 1 'WPF_Test.MainWindow' does not contain a definition for 'NavigationService' and no extension method 'NavigationService' accepting a first argument of type 'WPF_Test.MainWindow' could be found (are you missing a using directive or an assembly reference?) C:\Users\John\Dropbox\VS Projects\WPF Test\WPF Test\MainWindow.xaml.cs 29 18 WPF Test

I not sure where to add the definition for navigationservice. Everything I tried did not work. Please keep in mind I am a noob at programing, so I welcome any help.

Thanks,

John


John Lisenby developer of My PC Playbook

WPF: i want a control or code as same as wpf XAML file

$
0
0

Hi Everyone,

I want print the string in XML format just like WPF Xaml  in VS

in   

Please help me

Is there any control like ?

Page Navigation

$
0
0

I am using a Frame for page to page navigation. I am doing this navigation using the page objects.If I want to move back to a certain page with all its state of controls retained, how can I do it using JournalEntry ????

Close Login window and open mainwindow on Login

$
0
0
Hi,
I have a WPF app using MVVM with a login screen, on login, I need the login window to close and the Mainwindow to open.
Here's what I'm trying to do to achieve that:
In App.xaml.cs:
 protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var login = new Login();
            var loginVM = new LoginViewModel();
            loginVM.LoginCompleted += (sender, args) =>
                {
                    MainWindowViewModel mvm = new MainWindowViewModel();
                    MainWindow main = new MainWindow();
                    main.DataContext = mvm;
                    main.ShowDialog();
                  //tried main.Show() as well
                };

            login.DataContext = loginVM;
            login.ShowDialog();
        }
And in the Loginviewmodel.cs
 public void Login()
        {
            if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
            {
               //code to authenticate user
               ....

                //Call to the event
                RaiseLoginCompletedEvent();
              
            }
        }

        public event EventHandler LoginCompleted;
        private void RaiseLoginCompletedEvent()
        {
            var handler = LoginCompleted;
            if (handler != null)
                handler(this, EventArgs.Empty);
        }

The mainwindow opens fine after clicking the login button, but the login window doesn't close. It remains open too.What am I doing wrong here? I'm still learning WPF & MVVM.

Thank you

drop and drag Eventhandlers are not getting called for treeviewitem with heirarchaldatatemplate in wpf

$
0
0

Hello,

 I have created a TreeView with a custom HierarchicalDataTemplate to display my items on the tree. 

The items are being displayed just fine but I can't get the events of TreeViewItem to fire when something happens (like dragging, dropping etc). I only manage to get the MouseMove event to work when I try to drag and drop but even then the event handlers are not getting fired.

When I don't bind the items on the tree with my custom nodes then the events fire fine (i.e. I create some sample TreeViewItems).

Here is my xaml implementation of the TreeView

     
        <HierarchicalDataTemplate DataType="Procedure"
                           ItemsSource="{Binding
XPath=./*}">
            <StackPanel Orientation="Horizontal">
                               
                <TextBlock Margin="5,0,0,0"
                   Text="{Binding
XPath=@Name}"

}" />
            </StackPanel>
        </HierarchicalDataTemplate>

        <HierarchicalDataTemplate DataType="Step">
            <StackPanel Orientation="Horizontal">
                                <TextBlock Margin="5,0,0,0"
                           Text="{Binding
XPath=@Name}"/>
            </StackPanel>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="OptimizationSet"
                                  ItemsSource="{Binding XPath=./*}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Margin="5,0,0,0" Text="OptimizationSet" />
            </StackPanel>
        </HierarchicalDataTemplate>
    </Window.Resources>
    <Grid>
      
               <TreeView Name="tv"
                      ItemsSource="{Binding CollectionSource,Mode=TwoWay}" SelectedValuePath="{Binding SelectedStep,Mode=TwoWay}" AllowDrop="True">
                     <TreeView.ItemContainerStyle>
                        <Style TargetType="{x:Type TreeViewItem}">
                            <EventSetter Event="TreeViewItem.DragOver" Handler="treeView_DragOver"/>
                            <EventSetter Event="TreeViewItem.Drop" Handler="treeView_Drop"/>
                            <EventSetter Event="TreeViewItem.MouseMove" Handler="treeView_MouseMove"/>
                            <EventSetter Event="TreeViewItem.MouseDown" Handler="treeView_MouseDown"/>
                            <Setter Property="IsExpanded" Value="True" />
                            <Setter Property="AllowDrop" Value="True" />
                        </Style>

                    </TreeView.ItemContainerStyle>
                </TreeView>

            
   </Grid>

Set Document in DocumentViewer Async

$
0
0

Hi Experts,

i have a small problem with the DocumentViewer control. I am Rendering my document in a different thread, so far everything works fine, after that i want to display the fixeddocumentsequence in the viewer control. Here is where my problem starts i tried nearly everything but i cant set the document to the viewer, i always get a threading exception, that says that the document belongs to a differnt thread. I know what this exceptoin means, but i do not know why it's raised. 

Here is the code where I render the document and then try to display it in the viewer:

 System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
{
    Build();
    System.Windows.Documents.FixedDocumentSequence se = Document.FixedDocumentSequence;
    viewer.Dispatcher.BeginInvoke((Action)(() =>
    {
        viewer.Document = se;
    }));
}));
t.SetApartmentState(System.Threading.ApartmentState.STA);
t.IsBackground = true;
t.Start();

Can anyone help me with this "hopefully" easy Problem?

Kind Regards

Manu

 

Image Slider in WPF Surface 2.0

$
0
0
I want to build the image slider gallery in WPF Surface 2.0 (Pixelsense) such that when i move my finger from right to left or from left to right only one image should move at a time in the respective direction and accordingly the thumbnail should change. Any help will be very useful. 

Header nodes in a treeview bound to a dataset

$
0
0

Hello!

I've relational data in a dataset that should be displayed in a treeview hierarchically (e.g.  datatables "customer", "orders", "shipping notes" and "invoices" with parent-child relationships between"customer" - "orders", "orders" - "shipping notes" and "orders" - "invoices").

I used a hierachical data template that worked fine but I need to have something that I would call "header nodes". The bound treeview should look like this:

Customer 1

    Orders (<- Header node)

        Order 1

            Shipping Notes (<- Header node)

                Shipping Note 1

                Shipping Note 2

            Invoices (<- Header node)

                Invoice 1

        Order 2

        Order 3

Because the dataset structure corresponds to the database structure I'm not able to change the data model to archieve this.

What does the trick?

Thanks for your help!


Database Conection Issues.

$
0
0

Hi,

I am getting the following error when I attempt to connect to a database using the following from my WPF app. I have attached a screenshot of this error.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>

    <add name="anConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\an.mdf;Integrated Security=false;User Instance=false; user=sa;pwd=abc;"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

I have verified the account exists and the password is correct. I have tried using integrated security as well which results in a different error. I am unable to understand what causes this issue and have been working on it for several days now. Any help would be appreciated. 


Why it is slow to load a Addin UI in WPF+MAF

$
0
0

why it is slow to create a new WPF Control in this example?

Is there any way to speed it up?

The related code is under that page.
From Line 1 to Line 3 takes about 1-2 second.

1. this.wpfAddInHostView = wpfAddInToken.Activate<IWPFAddInHostView>(AddInSecurityLevel.Internet);// Get and display add-in UI
2. FrameworkElement addInUI = this.wpfAddInHostView.GetAddInUI();3. this.addInUIHostGrid.Children.Add(addInUI);

How to: Create an Add-In That Returns a UI

Thanks

Filtering a Collection WPF

$
0
0

Hi Guys,

I'm creating an application that allows a user to enter some Employee data into a EF entity model, using CRUD operations. 

So far, I have two ListViews. Here is an image to help understand what I have created so far.

What I want to achieve is when you select an item from Listbox1 (containing just the First name and surname) it just shows that specific employee details in Listbox2. Rather then showingall the results.

I have been advised to use Collection View Source. After researching a bit about it, I don't know where to start!

Here is the code of what I have currently.

ViewModel

private EmployeeViewModel selectedEmployee = null;
        public EmployeeViewModel SelectedEmployee
        {
            get
            {
                return selectedEmployee;
            }
            set
            {
                selectedEmployee = value;
                OnPropertyChanged("SelectedEmployee");
            }
        }

        private ObservableCollection<EmployeeViewModel> employeeList = null;
        public ObservableCollection<EmployeeViewModel> EmployeeList
        {
            get
            {
                return GetEmployees();
            }
            set
            {
                employeeList = value;
                OnPropertyChanged("EmployeeList");
            }
        }

        internal ObservableCollection<EmployeeViewModel> GetEmployees()
        {
            if (employeeList == null)
                employeeList = new ObservableCollection<EmployeeViewModel>();
            employeeList.Clear();

            foreach (DataObjects.Employee i in new EmployeeRepository().GetAllEmployees())
            {
                EmployeeViewModel c = new EmployeeViewModel(i);
                employeeList.Add(c);
            }
            return employeeList;
        }


xaml - Listbox 2;

<ListView Name="lsvEmployeeList" Height="170" Width="700"
                      ScrollViewer.VerticalScrollBarVisibility="Visible" 
                      ScrollViewer.HorizontalScrollBarVisibility="Visible" 
                      HorizontalAlignment="Center"
                      VerticalAlignment="Top"
                      IsSynchronizedWithCurrentItem="True"
                      ItemsSource="{Binding EmployeeList}" 
                      SelectedItem="{Binding SelectedEmployee, UpdateSourceTrigger=PropertyChanged}" ><ListView.View><GridView><GridViewColumn Header="Name" DisplayMemberBinding="{Binding }" Width="100" /></GridView></ListView.View></ListView>

xaml - listbox1

<ListView Height="330" HorizontalAlignment="Left" Name="lsNames" VerticalAlignment="Top" Width="170" 
                 ScrollViewer.VerticalScrollBarVisibility="Visible" 
                 ScrollViewer.HorizontalScrollBarVisibility="Visible" 
                 SelectedItem="{Binding SelectedEmployee}" 
                 ItemsSource="{Binding EmployeeList}" Margin="0,29,0,0"><ListView.View><GridView><GridViewColumn Header="FirstName" DisplayMemberBinding="{Binding FirstName}" Width="80" /><GridViewColumn Header="Surname" DisplayMemberBinding="{Binding Surname}" Width="80" /></GridView></ListView.View></ListView>

Any help would be much appreciated.

Many thanks,

Greg.


Viewing all 18858 articles
Browse latest View live