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

Copy/paste full row, full column, a cell on datagrid using MVVM?

$
0
0

What is the best way to implement on datagrid? As I am new on this, I had some researches but I am confused because there are some complicated implementations and easy ones? I try to understand the best way.

Adding simply selection mode and selection Unit doesnt help. Because it only copies the row but I cant paste it simply as a new row.

 SelectionMode="Extended" SelectionUnit="FullRow"  >

this approach in the article looks old to me. Not sure if there is anything new and much easier with newest framework. I am using MVVM light in my project.Attached is the sample project similar to my original project. can you please recommend me the best way for the following?

- Full Row(s) copy-paste

-1 or multiple columns copy-paste (optional)

- cell copy-paste


"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."


Use an usercontrol in a Window(WPF)

$
0
0

I build an user control "Board".

I want to use it in a window(WPF) "Game". I wrote :

Board board2 = new Board();

But it doesn't work. Have I to do s.th else ?(In the XAML...)

Thanks 

DataTrigger if Height Value is not"0"

$
0
0

Hello

I've this

<Image     Margin="9,3,10,0"     HorizontalAlignment="Left"  Width="14"  ><Image.Style><Style TargetType="{x:Type Image}"><Style.Triggers><DataTrigger Binding="{Binding Height, ElementName=myGridContent}" Value="135"><Setter   Property="Source"  Value="../../Images/icons/square_MINUS.png" /></DataTrigger><DataTrigger Binding="{Binding Height, ElementName=myGridContent}" Value="0"><Setter   Property="Source"  Value="../../Images/icons/square_PLUS.png" /></DataTrigger></Style.Triggers></Style></Image.Style></Image>

The above code works well. When myGridContent has the height"135", the image "square_MINUS.png" appears and "square_PLUS.png" appears when the height is "0".

Now, the height of  my myGridContent is not fixed, it can vary depending on the content. How to write theDataTrigger, to display

"square_PLUS.png" when the myGridContent height is "0"
and "square_MINUS.png" when the height is different from"0"?

Thanks for any help

WebBrowser script error when using google maps

$
0
0

Can't find anything related to this, so there is my entry on this.

Until a few weeks my app would work perfectly with webbrowser control and google maps(With this i mean, my app would show the route between 2 points on a webbrowser control). This week on monday i got a call from a customer complaining about a script error on my app, and that they couldnt see the google maps anymore, and indeed there is a problem, whenever i try to call the webbrowser from code i got a script error window with the information:

Error: InvalidCharachterError

Like i said this have been working so far until this week. I havent found anything on this problem.

Im using wpf with vb.net and on my usercontrol code i have:

Dim URLExample As String = "http://maps.google.nl/maps?f=d&hl=nl&geocode=&saddr=Lijnbaan+3d,+3252CK+Leiderdorp&daddr=3064+HW+Vleutenseweg+386-,+Utrecht&dirflg=h"       

web_view.Navigate(New Uri(URLExample ))

that url is just an example. The same url works on both google chrome and Internet explorer without any error, only when is used from the webbrowser control.

Things i have done:

Hide script errors with supress

add maps.google to trusted web sites

enable scripts on browser

change uri function to anotherURI("transparent", url) that i found on this forum(didnt work)

Thanks for reading and i hope you can help me.

Sorry if i sounded rude but i really dont meant to.

EDIT: even by going to https://maps.google.com i got the script error.

Regards,

Rui Nunes




Trigger Custom Property

$
0
0
Hello,

I have a window with a custom property, how can I use this custom property on trigger of window? This property is a enum type.

   <Window.Triggers> 
        <Trigger Property="PropertyName" Value="Value1"
            <Setter Property="Background" Value="Blue"/> 
        </Trigger> 
    </Window.Triggers> 

When I do that I receive this error message "'PropertyName' member is not valid because it does not have a qualifying type name."

 

Thanks,

 


Pati

WPF: how to toggle background color in xaml by using F1 key?

$
0
0

We want to show users different background colors when clicking F1 key.

Colors are defined as following:

<LinearGradientBrush x:Key="StatusBackround1"

EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#FF88AED0" Offset="0"/><GradientStop Color="#FF5286B2" Offset="1"/></LinearGradientBrush>

<LinearGradientBrush x:Key="StatusBackground2"
		EndPoint="0.5,1" StartPoint="0.5,0"><GradientStop Color="#FFCCDDED" Offset="0"/><GradientStop Color="#FFB7D5F2" Offset="1"/></LinearGradientBrush>

we know how to implement it in code behind.

protected override void OnPreviewKeyDown( KeyEventArgs e )
{
     if ( e.Key == Key.F3 )
     {
        ToggleTabStyle();
        e.Handled = true;
     }
}

static bool showTab2 = false;
private void ToggleTabStyle()
{
     LinearGradientBrush statusBackground;
     showTab2 = !showTab2 ;
     if (showTab2 )
     {
         statusBackground = Application.Current.Resources["StatusBackground2"] as LinearGradientBrush;
     }
     else
     {
       statusBackground = Application.Current.Resources["StatusBackround1"] as LinearGradientBrush;
     }
     this.rectagleStatus.Fill = statusBackground;
}

How easy to implement in xaml? Thx!


JaneC


Dynamic Width Text Button

$
0
0

Hi,

Can someone advise if it's possible to implement a button with a dynamic width that matches the text content?

At the moment I have:

<Button x:Name="btnLabelSupport" Click="btnSupport_Click" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="459,80,310,0" Width="61" Height="20" RenderTransformOrigin="0.075,0.55"><Button.Style><Style TargetType="{x:Type Button}"><Setter Property="Opacity" Value="0.7"/><Style.Triggers><Trigger Property="IsMouseOver" Value="True"><Setter Property="Opacity" Value="1"/></Trigger></Style.Triggers></Style></Button.Style><Button.Template><ControlTemplate TargetType="{x:Type Button}"><Grid Margin="0,0,-80,0"><Rectangle Fill="Transparent"/><TextBlock HorizontalAlignment="Left"
        					TextWrapping="Wrap"
        					Text="SUPPORT"
        					VerticalAlignment="Top"
        					Foreground="White" RenderTransformOrigin="1.118,0.688" Width="60" Height="20"/></Grid></ControlTemplate></Button.Template></Button>

This is fine, but if I implement different languages later the width will be an issue.

Thanks

WPF WebBrowser Control Security Message After Loading Local XML File

$
0
0

When I use the .Source property of the WebBrowser control, it displays the XML file I pointed to, but then puts a security banner at the top, stating that some content has been disabled.  I can't figure out how to stop that warning from appearing.  I've played with IE security settings, to no avail.

I've found some articles about putting a "mark of the web" tag inside the XML file, but I can't do that because the files are created by a 3rd-party application, and I can't edit all of them.

Isn't there a simple way to just turn off the feature for the WebBrowser control without messing with my IE security settings?

Thanks...


Ron Mittelman


How to bind my UserControl to the Mainwindow (correctly)?

$
0
0

I created a sample WPF app for binding a list to a datagrid.  The app appears to work fine.  However, in the designer (VS2012) I am getting an error in MainWindow.xaml that it cannot create an instance of my UserControl.  Below are pictures of MainWindow.xaml and my usercontrol.xaml and all the source code.  What is the correct way to bind my usercontrol to MainWindow.xaml?

Model folder -- Expense class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;

namespace myDatagridBindingSample.Model
{
    public class Expense : INotifyPropertyChanged
    {
        private string _name;
        private double _amount;

        public string Name
        {
            get { return _name; }
            set { _name = value; NotifyPropertyChanged("Name"); }
        }

        public double Amount
        {
            get { return _amount; }
            set { _amount = value; NotifyPropertyChanged("Amount"); }
        }


        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

ViewModel folder -- DatagridDisplayViewModel class 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using myDatagridBindingSample.Model;
using System.ComponentModel;

namespace myDatagridBindingSample.ViewModel
{
    class DatagridDisplayViewModel : INotifyPropertyChanged
    {
        private BindingList<Expense> _expenses;
        private double _totalExpense;

        public double TotalExpense
        {
            get { return _totalExpense = _expenses.Sum(x => x.Amount); }
            set { _totalExpense = value; }
        }

        public BindingList<Expense> Expenses
        {
            get { return _expenses; }
            set
            {
                _expenses = value;
                if (_expenses != null)
                {
                    _expenses.ListChanged += (o, e) => NotifyPropertyChanged("TotalExpense");
                }
                //NotifyPropertyChanged("Expenses");
            }
        }

        public DatagridDisplayViewModel()
        {
            Expenses = new BindingList<Expense>
                            {
                                new Expense() {Name = "Gas", Amount = 1000},
                                new Expense() {Name = "Electricity", Amount = 1000},
                                new Expense() {Name = "Internet", Amount = 100},
                                new Expense() {Name = "Water", Amount = 100},
                                new Expense() {Name = "Misc", Amount = 1000}
                            };
        }

        public event PropertyChangedEventHandler PropertyChanged;
        //private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        private void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

ViewModel folder -- UserControl -- DatagridDisplay.xaml

<UserControl x:Class="myDatagridBindingSample.ViewModel.DatagridDisplay"
             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"
             mc:Ignorable="d"
             xmlns:vm="clr-namespace:myDatagridBindingSample.ViewModel"
             d:DesignHeight="300" d:DesignWidth="300"><UserControl.DataContext><vm:DatagridDisplayViewModel /></UserControl.DataContext><Grid><Grid.RowDefinitions><RowDefinition/><RowDefinition/></Grid.RowDefinitions><DataGrid ItemsSource="{Binding Expenses, Mode=TwoWay}" AutoGenerateColumns="True" Grid.Row="0"/><TextBlock Grid.Row="1"><Run Text="Total: "/><Run Text="{Binding TotalExpense}"/></TextBlock></Grid></UserControl>

MainWindow.xaml

<Window x:Class="myDatagridBindingSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:myDatagridBindingSample.ViewModel"
        Title="MainWindow" Height="350" Width="525"><vm:DatagridDisplay /></Window>

----UserControl picture

---MainWindow.xaml  pictures


Rich P

WPF: How to make DataGrid Cell style?

$
0
0

Our WPF application uses WPF DataGrid.

we have use the following style.

<!-- Set grid cell vertical alignment to cetner--><Style x:Key="Body_Content_DataGrid_Centering"
        TargetType="{x:Type DataGridCell}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type DataGridCell}"><Grid Background="{TemplateBinding Background}" VerticalAlignment="Stretch"><ContentPresenter VerticalAlignment="Center"/></Grid></ControlTemplate></Setter.Value></Setter></Style>
<DataGrid
      CellStyle="{StaticResource Body_Content_DataGrid_Centering}"</DataGrid>
 

What we notice, when click on cell try to edit in the cell, its edited area only restricts in the Vertical center (very narrow area). It does not use the whole cell height. If we do not apply above style, the cell text only displays on top and not align on the center vertically.

We actually need the each cell displays text in one line (in vertically center) if cell text is not too long.

However, when cell text too long, it will automatically wrap to second lines.

When edit cell, it highlight the whole cell as edit area.

How do we achieve that? Thx!


JaneC


Win32Exception from ReleaseCapture call in Window.ShowDialog

$
0
0

Hi,

We are getting "The operation completed successfully" Win32 exception in a very specific use case. In our application there are some old windows made in Progress OpenEdge that can be opened as children of a main window. The problem occurs when a user opens a context menu in one of them and then tries to open a modal window with a shortcut, they get the following exception:

System.ComponentModel.Win32Exception (0x80004005): The operation completed successfully
at MS.Win32.SafeNativeMethods.ReleaseCapture()
at System.Windows.Window.ShowDialog()

[the next line is already our ShowModalWindow method]

The relevant fragment of System.Windows.Window class on Reference Source has some interesting comments:

if (hWndCapture != IntPtr.Zero)
{
    //
    // NOTE: hamidm -- 7/14/04
    // EnableWindow(false) (called from EnableThreadWindows(false)
    // sends WM_CANCELMODE to the window, so we don't need
    // to send it again.  However, if we change our impl
    // of dialog such that we don't disable all windows on the
    // thread, then we would need this call. Keeping this code here
    // until we finish the Dialog task # 18498

    // UnsafeNativeMethods.SendMessage(hWndCapture,
    //                                WindowMessage.WM_CANCELMODE,
    //                                IntPtr.Zero,
    //                                IntPtr.Zero);

    // hWndCapture = UnsafeNativeMethods.GetCapture();
    // if (hWndCapture != IntPtr.Zero)
    // {
        // PS # 862892
        // WCP: Investigate whether ReleaseCapture is needed in ShowDialog
        SafeNativeMethods.ReleaseCapture();
    // }
}

Simply catching an exception causes the main window to freeze, but leaves the old form operational.

Any ideas what might be causing this behavior and how can we fix it?

Thanks,
Marek

How to override the onTouchUp in the user control which can be used to fire the event not only on this user control, but whole application

$
0
0
 I am a new to the C# and WPF. Right now, I want to override onTouchUp event in my user control. Then I can add user control in the references for reuse. The problem is each time I want to test this event on the application, the event only fire at area of user control, not whole screen. Anyone has solution for this?

Changing Combo Box values

$
0
0

Hi all,

I am using a WPF ComboBox, and the requirement is that if the user tries to change the value without opening the combo box, the combo box needs to dropdown. So if a user focuses on the combo box and then press one of the arrow keys, the combo box should drop down. The value should not change without dropping down.

Is there any event that I can capture to detect whether the user has changed the value using keyboard without opening the dropdown? Or is there any other way of accomplishing the same behavior?

Thanks!

Application using Prism library can be without a module?

$
0
0

Hi,

Can you please let me know if an application using Prism library can be without a module?

Thanks,

Santosh

Raise Key pressed event

$
0
0

Hello, any know how can I raise a key press event throw code. For example I want to simulate that the user has press the A Key. How can I do that throw code?

 

Thanks a lot !!


WPF: How to make DataGrid Cell style to allow cell text displays in center of celll and also allow text wrap if text too long?

$
0
0

Our WPF application uses WPF DataGrid. It requires text displays in center of cell if text fit in one line. If text too long, wrap text into two lines.

we have use the following style.

<!-- Set grid cell vertical alignment to cetner--><Style x:Key="Body_Content_DataGrid_Centering"
        TargetType="{x:Type DataGridCell}"><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type DataGridCell}"><Grid Background="{TemplateBinding Background}" VerticalAlignment="Stretch"><ContentPresenter VerticalAlignment="Center" Height="45"/></Grid></ControlTemplate></Setter.Value></Setter></Style>
<DataGrid
      CellStyle="{StaticResource Body_Content_DataGrid_Centering}"</DataGrid>
 

What we notice, when click on cell try to edit in the cell, its edited area only restricts in the Vertical center (very narrow area). It does not use the whole cell height. If we do not apply above style, the cell text only displays on top and not align on the center vertically.

We actually need the each cell displays text in one line (in vertically center) if cell text is not too long.

However, when cell text too long, it will automatically wrap to second lines.

When edit cell, it highlight the whole cell as edit area.

How do we achieve that? Thx!


JaneC



Deleting Item From Datagrid (Entity Framework)

$
0
0

I have a WPF C# application.  I am using the entity framework to manage my data.

I have a datagrid and I want to write code so when a datagrid item is removed, it is also removed from the entity framework collection the item was stored in.

My current code is:

        private void otherDataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                var grid = (DataGrid)sender;
                if (grid.SelectedItems.Count > 0)
                {
                    var Res = MessageBox.Show("Are you sure you want to delete " + grid.SelectedItems.Count + " Employees?", "Deleting Records", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                    if (Res == MessageBoxResult.Yes)
                    {
                        foreach (var row in grid.SelectedItems)
                        {
                            User employee = row as User;
                            _context.Users.Remove(employee);
                        }
                        _context.SaveChanges();
                        MessageBox.Show(grid.SelectedItems.Count + " Employees have being deleted!");
                    }
                }
            }
        }

However, this throws the error:

An unhandled exception of type 'System.NullReferenceException' occurred in Asset Manager.exe

Additional information: Object reference not set to an instance of an object.

Which occurs at the line:

_context.Users.Remove(employee);

Any idea why it isn't picking up the selected line in the datagrid as an object?

how to avoid that the last column in a datagrid increase the width out of the window?

$
0
0

I have a datagrid with this configuraction:

<DataGrid.Columns><DataGridTextColumn Header="Column01" Binding="{Binding Property1, Mode=OneWay}"/><DataGridTextColumn Header="Column02" Binding="{Binding Property2, Mode=OneWay}"/><DataGridTextColumn Header="Column03" Binding="{Binding Property3, Mode=OneWay}"/></DataGrid.Columns>

The last column is a description, so the text can be a bit large. so I would like that the width don't be wnough greater than makes the datagrid has a width out side the window.

For this, I have read that I can use Width="Auto" in all the columns and in the last column width="*", but in this case all the coloumns has a very low width so I can't read anything.

The code that I have used in this case is:

<DataGrid.Columns><DataGridTextColumn Header="Column01" Binding="{Binding Property1, Mode=OneWay}" Width=""Auto"/><DataGridTextColumn Header="Column02" Binding="{Binding Property2, Mode=OneWay}" Width=""Auto"/><DataGridTextColumn Header="Column03" Binding="{Binding Property3, Mode=OneWay}" Width=""*"/></DataGrid.Columns>

I am using visual studio community edition and wpf 4.5.1.

Thank so much,

How to add text to a polygon shape?

$
0
0

I created a triangle:

<Polygon Name="triangle_top"  Points="0,0 130,0, 130,130" Stroke="Black" />

I would like to add text to it without adding a label.

how should I do it?

[WPF] DatePicker: show only date

$
0
0

Hi,

in my grid I'm using a DatePicker (for show and edit), I would show only date and hide time so I force the view with StringFormat, but I not works.

Why?

<DataGridTemplateColumn Header="{StaticResource datagridDatetime}"><DataGridTemplateColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding DateTime, Mode=OneWay, StringFormat='dd/MM/yyyy'}"></TextBlock></DataTemplate></DataGridTemplateColumn.CellTemplate><DataGridTemplateColumn.CellEditingTemplate><DataTemplate><DatePicker SelectedDate="{Binding DateTime, StringFormat='dd/MM/yyyy'}"   /></DataTemplate></DataGridTemplateColumn.CellEditingTemplate></DataGridTemplateColumn>

Thanks.

Viewing all 18858 articles
Browse latest View live


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