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

KeyGesture bound to RoutedUICommand not working with Key.Left but working with other keys

$
0
0

I have just started adding keyboard support for my application. It already had multiple commands implemented but they are all bound to controls, like menu items. Most UI elements in my application are custom controls. I define routed UI commands, like this:

public static RoutedUICommand LeftAlignProp { get { return LeftAlignCmd; } }
private static RoutedUICommand LeftAlignCmd = new RoutedUICommand("Align selection left", "LeftAlign", typeof(ProgramListingSectionT));

Then, in the constructor I create the bindings:

CommandBindings.Add(new CommandBinding(LeftAlignProp, LeftAlignExecute, LeftAlignCanExecute));
LeftAlignProp.InputGestures.Add(new KeyGesture(Key.NumPad4, ModifierKeys.Control)); // Ctrl+LeftArrow

The handlers are pretty standard, too:

private void LeftAlignExecute(object sender, ExecutedRoutedEventArgs e) // Carry the actions of the "left align" command
    {
      LeftAlignSelection();
    }
private void LeftAlignCanExecute(object sender, CanExecuteRoutedEventArgs e)  // Allow copying by default (may be overridden)
    {
      e.CanExecute = SelectedCodeEnvelopes.Count > 0; // Only when there is a selection
    }

I don't know if any of that matters because everything works - the above code works fine, I also have other commands (like Ctrl+C for "copy", etc.) My problem is that if I were to replace the Key.NumPad4 above (which is the left arrow on the numeric keypad) with Key.Left, or any of the dedicated arrow keys (i.e., not on the numeric keypad), the command doesn't fire.

Nothing weird is going on, i.e., there is nothing else handling keyboard events (that I intended), much less specifically the arrow keys. The keyboard/driver/etc. are all standard. I even tried handling the OnKeyDown and the related events to try and figure it out but those don't seem to fire at all. But it shouldn't matter, it's input gestures on a command. And it's not like it isn't working for me at all; it is only the arrow keys - all other keys I've tried work fine. What a mystery!

Any ideas?

Kamen


Currently using Visual Studio 2010 SP1, native C++ (Windows API) and C# (.Net, WPF), on Windows 7 64-bit; Mountain Time zone.




Date Time

$
0
0
Hi,
please how do i get the date alone from the datepicker of WPF C#. i get this after choosing the date 23/03/2013 12:00AM i only want 23/03/2013.
i Have not seen any method of extracting this from the datepicker please help.

thanks

Get data from RotateTransform3D in C#

$
0
0

hi, in my code i set that RotateTransform3D as a children inside a Transform3DGroup with this:

myGroupArray[0].Children.Add(newRotateTransform3D(newAxisAngleRotation3D(newVector3D(0,0,1),Convert.ToDouble(5)),newPoint3D(0,0,0)));

and in another function i try to recover my "5" with this:

RotateTransform3D rotation =newRotateTransform3D();
rotation =(RotateTransform3D)myGroupArray[0].Children[0];

now, even doing

MessageBox.Show(rotation.Rotation.Angle.ToString());

results in error because Rotation3D does not contain an Angle property

How can i get my "5" back?

Making 'IsMouseOver' open submenu items consistently

$
0
0

I am trying to define a style for menu items so when the mouse is over the main menu item, the next level of sub menu items will automatically open. So I created a style for MenuItem and made a trigger for 'IsMouseover' to cause 'IsSubmenuOpen' to become 'true'. It works fine once, but after clicking on a sub menu item, let it close, then next time the mouse is over the main menu, the sub menu items no longer opens automatically.

I looked at the MenuItem control template and see the 'IsSubmenuOpen' is bounded via TemplateBinding, so I would hope my style that sets this should override every time.

I am using VS 2012 with .Net Framework 4.5.

The XAML follows. Notice the 'tool tips menu item':

<Menu Height="28"

      Margin="10, 3, 0, 0"

      KeyboardNavigation.TabNavigation="Cycle"

      Background="{StaticResource Background1Key}"

      Foreground="{StaticResource Foreground1Key}" >

   <Menu.ItemsPanel>

        <ItemsPanelTemplate>

            <Grid VerticalAlignment="Center"/>

        </ItemsPanelTemplate>

   </Menu.ItemsPanel>

   <MenuItem Name="ViewMenu"

             Style="{StaticResource MainMenuItem}"

             Header="_View">

       <MenuItem Name="ToolTipsMenuItem"

                 Style="{StaticResource ToolTipsMenuItem}"/>

       </MenuItem>

   </Menu>

The styles are:

<!-- For tool tips on/off menu item -->

<Style x:Key="ToolTipsMenuItem" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource SubMenuItem}">

    <Setter Property="Header" Value="_Show ToolTips"/>

    <Setter Property="IsCheckable" Value="True"/>

    <Setter Property="IsChecked" Value="{Binding Source={x:Static p:Settings.Default},

            Path=ShowToolTips, Mode=TwoWay}"/>

</Style>

<Style x:Key="SubMenuItem" TargetType="{x:Type MenuItem}">

     <Setter Property="Background" Value="{StaticResource Background2Key}"/>

     <Setter Property="Foreground" Value="{StaticResource Foreground2Key}"/>

</Style>

<Style x:Key="MainMenuItem" TargetType="{x:Type MenuItem}" >

     <Setter Property="Background" Value="Transparent"/>

     <Setter Property="Foreground" Value="{StaticResource Foreground1Key}"/>

     <Style.Triggers>

          <Trigger Property="IsMouseOver" Value="True">

              <Setter Property="IsSubmenuOpen" Value="True"/>

               <Setter Property="Cursor" Value="Hand"/>

          </Trigger>

     </Style.Triggers>

</Style>

So the first time the mouse is over the main menu, the tool tip sub menu item opens, but only once. If I click on the tooltip menu item to change it, it changes and closes. But now the mouse over the main menu won't auto open the sub menu tool tip item.

Also, I hear a faint chuckling. I think the system is laughing at me!

Thanks for any help!


philb222



Touch Event responsiveness/performance/delay

$
0
0

When I manipulating a framework element with MouseEvents everything works fine andit responds instantly without any delay. But when I manipulate this element with my finger (TouchEvents) the manipulated element lags behind my finger and keep get manipulated after my finger is raised up from the screen.

It seems that the MouseEvents are handled different in background.

Is there any solution for this problem? Hopefully someone can help me with this.



Image shows during design time but not during runtime

$
0
0

I am pretty new to wpf and had to look up exactly how to use resources. I am trying to display our company's logo on a window which correctly shows in xaml/design time but does not show on runtime no matter if its set to resource, embedded resource, content, copy always, or do not copy. These are the two lines of code I have tried and again both work in design time but not run time.

<Image Grid.Column="3" Margin="2" Source ="/AMS_WPF;component/logo.png"></Image>

and the second line is 

<Image Grid.Column="3" Margin="2" Source ="pack://application:,,,/Resources/logo.png"></Image>

The way I added the resource image to my project resource folder is by going to the project properties>resources>add existing resource and browsing to it

WPF Datagrid Binding Problem

$
0
0

I have write simple form with new/edit/delete function. but I add new item and edit the existing item, that is no problems. when i delete item in the grid, the error message is appear on the screen. Anyone can suggest me this problems. I will appreciate it. Below is my code.

<Window x:Class="FBPOS.frmGroup"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Group" Height="768" Width="1024">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="360"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="60"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">
            <DataGrid x:Name="grdGroup" HorizontalAlignment="Left" VerticalAlignment="Top" Width="1020" Height="350" CanUserAddRows="False" AutoGenerateColumns="False" AlternatingRowBackground="Azure" SelectionMode="Single" SelectionChanged="grdGroup_SelectionChanged" IsReadOnly="True">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding GrpId}" Width="70" Header="ID"/>
                    <DataGridTextColumn Binding="{Binding GrpDescription}" Width="200" Header="Description"/>
                    <DataGridTextColumn Binding="{Binding GrpDescription2}" Width="200" Header="2nd Description"/>
                    <DataGridTextColumn Binding="{Binding Remarks}" Width="100" Header="Remarks"/>
                    <DataGridTextColumn Binding="{Binding KitchenPrinter1}" Width="100" Header="Kitchen Printer 1"/>
                    <DataGridTextColumn Binding="{Binding KitchenPrinter2}" Width="100" Header="Kitchen Printer 2"/>
                    <DataGridTextColumn Binding="{Binding KitchenPrinter3}" Width="100" Header="Kitchen Printer 3"/>
                    <DataGridTextColumn Binding="{Binding KitchenPrinter4}" Width="100" Header="Kitchen Printer 4"/>
                    <DataGridTextColumn Binding="{Binding LastModified}" Width="100" Header="Last Modified"/>
                    
                    
                </DataGrid.Columns>
            </DataGrid>

        </Grid>
        <Grid Grid.Row="1">
            <Grid Margin="30,20,20,20">
                <Grid.RowDefinitions>
                    <RowDefinition Height="50" />
                    <RowDefinition Height="50"/>
                    <RowDefinition Height="50"/>
                    <RowDefinition Height="50"/>
                    <RowDefinition Height="50"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100"/>
                    <ColumnDefinition Width="400"/>
                    <ColumnDefinition Width="100"/>
                    <ColumnDefinition Width="200"/>
                </Grid.ColumnDefinitions>
                <Label Content="Group ID" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="0" Grid.Row="0"/>
                <TextBox x:Name="txtGroupId" HorizontalAlignment="Left" Height="35" TextWrapping="Wrap" VerticalAlignment="Center" Width="200" Grid.Column="1" Grid.Row="0" MaxLength="7"/>
                <Label Content="Date" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="2" Grid.Row="0"/>
                <Label x:Name="lblCurrentDate" Content="CurrentDate" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="3" Grid.Row="0" Width="200" Height="35"/>
                <Label Content="Description" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="0" Grid.Row="1"/>
                <TextBox x:Name="txtDescription" HorizontalAlignment="Left" Height="35" TextWrapping="Wrap" VerticalAlignment="Center" Width="200" Grid.Column="1" Grid.Row="1" MaxLength="30" KeyUp="txtDescription_KeyUp"/>
                <Label Content="2nd Description" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="2" Grid.Row="1"/>
                <TextBox x:Name="txt2ndDescription" HorizontalAlignment="Left" Height="35" TextWrapping="Wrap" VerticalAlignment="Center" Width="200" Grid.Column="3" Grid.Row="1" MaxLength="30"/>
                <Label Content="Remarks" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="0" Grid.Row="2"/>
                <TextBox x:Name="txtRemarks" HorizontalAlignment="Left" Height="35" TextWrapping="Wrap" VerticalAlignment="Center" Width="200" Grid.Column="1" Grid.Row="2" MaxLength="50"/>                
                <Label Content="Printer 1" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="0" Grid.Row="3"/>
                <ComboBox x:Name="cboPrinter1" Grid.ColumnSpan="2" HorizontalAlignment="Left" VerticalAlignment="Center" Width="120" Grid.Column="1" Grid.Row="3" MinWidth="200" MinHeight="35" ShouldPreserveUserEnteredPrefix="True" IsEditable="True" />
                <Label Content="Printer 2" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="2" Grid.Row="3" />
                <ComboBox x:Name="cboPrinter2" Grid.ColumnSpan="2" HorizontalAlignment="Left" VerticalAlignment="Center" Width="120" Grid.Column="3" Grid.Row="3" MinWidth="200" MinHeight="35" IsEditable="True"/>
                <Label Content="Printer 3" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="0" Grid.Row="4"/>
                <ComboBox x:Name="cboPrinter3" Grid.ColumnSpan="2" HorizontalAlignment="Left" VerticalAlignment="Center" Width="120" Grid.Column="1" Grid.Row="4" MinWidth="200" Padding="0" Panel.ZIndex="-12" MinHeight="35" IsEditable="True" />
                <Label Content="Printer 4" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Column="2" Grid.Row="5"/>
                <ComboBox x:Name="cboPrinter4" Grid.ColumnSpan="2" HorizontalAlignment="Left" VerticalAlignment="Center" Width="120" Grid.Column="3" Grid.Row="4" MinWidth="200" MinHeight="35" Padding="0" IsEditable="True"/>
                


            </Grid>
            
        </Grid>
        <Grid Grid.Row="3" Margin="30,0,0,0">
            <StackPanel Orientation="Horizontal" Margin="5">
                <Button x:Name="btnNew" Content="New" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="45" Click="btnNew_Click"/>
                <Button x:Name="btnSave" Content="Save" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="45" Margin="10,0,0,0" Click="btnSave_Click"/>
                <Button x:Name="btnDelete" Content="Delete" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Height="45" Margin="10,0,0,0" Click="btnDelete_Click"/>
            </StackPanel>
            
        </Grid>
    </Grid>
</Window>

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.Shapes;
using System.Printing;
using System.Data.SqlClient;
using System.Data;

namespace FBPOS
{
    /// <summary>
    /// Interaction logic for frmGroup.xaml
    /// </summary>
    public partial class frmGroup : Window
    {
        bool status,errmessage;
        SQLConnectionString sqlconn;
        

        public frmGroup()
        {
            InitializeComponent();
            status = false;
            sqlconn = new SQLConnectionString();
            FillDataGrid();
            PopulateInstalledPrintersCombo();            
        }
        private void FillDataGrid()
        {
            try
            {                
                SqlCommand sqlfilldata = new SqlCommand("SELECT [GrpId],[GrpDescription],[GrpDescription2],[Remarks],[LastModified],[KitchenPrinter1],[KitchenPrinter2],[KitchenPrinter3],[KitchenPrinter4] FROM [dbo].[Groups] Order by GrpId", sqlconn.GetDatabaseConnection());
                SqlDataAdapter sqldagroup = new SqlDataAdapter(sqlfilldata);
                DataTable dtGroups = new DataTable("Groups");                
                sqldagroup.Fill(dtGroups);
                //grdGroup.ItemsSource = null;
                
                grdGroup.ItemsSource = dtGroups.DefaultView;
                
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                
            }
            
        }
        private void btnNew_Click(object sender, RoutedEventArgs e)
        {
            ClearData();
            lblCurrentDate.Content = DateTime.Now.ToShortDateString();
            status = true;
            txtGroupId.IsReadOnly = false;
            txtGroupId.Focus();            
        }
        private void ClearData()
        {
            txtGroupId.Text = string.Empty;
            txtDescription.Text = string.Empty;
            txt2ndDescription.Text = string.Empty;
            txtRemarks.Text = string.Empty;
            cboPrinter1.Text = string.Empty;
            cboPrinter2.Text = string.Empty;
            cboPrinter3.Text = string.Empty;
            cboPrinter4.Text = string.Empty;
        }
        private void PopulateInstalledPrintersCombo()
        {            
            // Add list of installed printers found to the combo box.
            // The pkInstalledPrinters string will be used to provide the display string.
            cboPrinter1.Items.Clear();
            cboPrinter2.Items.Clear();
            cboPrinter3.Items.Clear();
            cboPrinter4.Items.Clear();
            cboPrinter1.Items.Add(string.Empty);
            cboPrinter2.Items.Add(string.Empty);
            cboPrinter3.Items.Add(string.Empty);
            cboPrinter4.Items.Add(string.Empty);            
            LocalPrintServer printServer = new LocalPrintServer();
            PrintQueueCollection printqueueOnLocalServer = printServer.GetPrintQueues();
            foreach (PrintQueue printer in printqueueOnLocalServer)
            {
                cboPrinter1.Items.Add(printer.Name);
                cboPrinter2.Items.Add(printer.Name);
                cboPrinter3.Items.Add(printer.Name);
                cboPrinter4.Items.Add(printer.Name);
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            errmessage = false;
            if (txtGroupId.Text== string.Empty)
            {
                Properties.Settings.Default.ErrorMessage = "Group Id field can't be empty.\n";
                Properties.Settings.Default.Save();
                errmessage = true;
            }
            if (txtDescription.Text == string.Empty)
            {
                Properties.Settings.Default.ErrorMessage = Properties.Settings.Default.ErrorMessage.ToString() + "Description field can't be empty.\n";
                Properties.Settings.Default.Save();
                errmessage = true;
            }                        
            if (errmessage == true)
            {
                MessageBox.Show(Properties.Settings.Default.ErrorMessage.ToString());
                Properties.Settings.Default.ErrorMessage = string.Empty;
                Properties.Settings.Default.Save();
            }
            else
            {
                try
                {                    
                    if (status == true)
                    {
                        SqlCommand cmdcheck = new SqlCommand("sp_ValidateGroupId", sqlconn.GetDatabaseConnection());
                        cmdcheck.CommandType = CommandType.StoredProcedure;                       
                        SqlParameter myParm = cmdcheck.Parameters.Add("@GroupId", SqlDbType.NVarChar, 7);
                        myParm.Value = txtGroupId.Text;
                        SqlParameter myReturnParm = cmdcheck.Parameters.Add("@returnvalue",SqlDbType.Int);
                        myReturnParm.Direction = ParameterDirection.ReturnValue;
                        object chkexist;
                        chkexist = cmdcheck.ExecuteScalar();
                        if (Convert.ToBoolean(myReturnParm.Value) == true)
                        {
                            MessageBox.Show("Group Id * " +txtGroupId.Text + " * is already Exist.");
                            txtGroupId.SelectionStart = 0;
                            txtGroupId.SelectionLength = txtGroupId.Text.Length;
                        }
                        else
                        {
                            SqlCommand cmdnew = new SqlCommand("INSERT INTO [dbo].[Groups] ([GrpId],[GrpDescription],[GrpDescription2],[Remarks],[LastModified],[KitchenPrinter1],[KitchenPrinter2],[KitchenPrinter3],[KitchenPrinter4]) VALUES ('" + txtGroupId.Text + "','" + txtDescription.Text + "','" + txt2ndDescription.Text + "','" + txtRemarks.Text + "','" + Convert.ToDateTime(lblCurrentDate.Content.ToString())+"','" + cboPrinter1.Text + "','" + cboPrinter2.Text + "','" + cboPrinter3.Text + "','" + cboPrinter4.Text +"')",sqlconn.GetDatabaseConnection());
                            cmdnew.CommandTimeout = 15;
                            cmdnew.ExecuteNonQuery();
                            
                            MessageBox.Show("Record is successfully saved.");
                            status = false;
                            txtGroupId.IsReadOnly = true;
                            FillDataGrid();
                        }
                        cmdcheck.Dispose();
                    }
                    else
                    {
                        SqlCommand cmdedit = new SqlCommand("UPDATE GROUPS Set GrpDescription='" + txtDescription.Text + "', GrpDescription2 ='" + txt2ndDescription.Text + "', Remarks = '" + txtRemarks.Text + "', LastModified = '" + txtRemarks.Text + "', KitchenPrinter1 = '" + cboPrinter1.Text + "', KitchenPrinter2 = '" + cboPrinter2.Text + "', KitchenPrinter3 = '" + cboPrinter3.Text + "', KitchenPrinter4= '" + cboPrinter4.Text + "' where GrpId = '" + txtGroupId.Text +"';",sqlconn.GetDatabaseConnection());                       
                        cmdedit.ExecuteNonQuery();
                        cmdedit.Dispose();
                        FillDataGrid();
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {                    
                    
                }                
            }                            
        }        
        private void txtDescription_KeyUp(object sender, KeyEventArgs e)
        {
            txt2ndDescription.Text = txtDescription.Text;
        }        
        private void grdGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            txtGroupId.Text = (grdGroup.SelectedItem as DataRowView).Row["GrpId"].ToString();
            lblCurrentDate.Content = (grdGroup.SelectedItem as DataRowView).Row["LastModified"].ToString();
            txtDescription.Text =  (grdGroup.SelectedItem as DataRowView).Row["GrpDescription"].ToString();
            txt2ndDescription.Text = (grdGroup.SelectedItem as DataRowView).Row["GrpDescription2"].ToString();
            txtRemarks.Text = (grdGroup.SelectedItem as DataRowView).Row["Remarks"].ToString();            
            cboPrinter1.Text = (grdGroup.SelectedItem as DataRowView).Row["KitchenPrinter1"].ToString();
            cboPrinter2.Text = (grdGroup.SelectedItem as DataRowView).Row["KitchenPrinter2"].ToString();
            cboPrinter3.Text = (grdGroup.SelectedItem as DataRowView).Row["KitchenPrinter3"].ToString();
            cboPrinter4.Text = (grdGroup.SelectedItem as DataRowView).Row["KitchenPrinter4"].ToString();
            status = false;
            txtGroupId.IsReadOnly = true;
        }

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {            

            if (grdGroup.HasItems == true && grdGroup.SelectedIndex != -1)
            {
                SqlCommand sqldetete;
                string delstr = (grdGroup.SelectedItem as DataRowView).Row["GrpId"].ToString();

                MessageBoxResult msresult = MessageBox.Show("Are you sure to delete '"+ delstr + "'", "Confirm", MessageBoxButton.YesNo);
                if (msresult == MessageBoxResult.Yes)
                {                    
                    try
                    {
                        sqldetete = new SqlCommand("Delete from Groups where GrpID = '" + delstr + "'", sqlconn.GetDatabaseConnection());
                        sqldetete.ExecuteNonQuery();
                        FillDataGrid();                       
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.ToString());

                    }
                                     
                }
            }
        }
       
    }
}

How to set VIEW object to VIEWMODEL entity data

$
0
0

I have a ViewModel that exposes multiple entities within it to a single View, with multiple datagrids on it.

One of the things on the VIEW is a calendar object that I want to create new appointments.  The calendar object has it's own appointment model that I need to map to my entity data in my ViewModel.  However since I cannot expressly expose my entity class directly to my View I am wondering what the best way to do this mapping would be.

Would it be to loop through a list of the entities in the ViewModel and then raise an event so that the View adds a new appointment and sets the properties of the appointment to the properties exposed in my ViewModel that have been set by the looping through the list of entities?

I was hoping to just iterate through my list of entities from within the view (not a problem to loop through the list itself), but since the entity class is not exposed in the View, it does not what the entity looks like as I loop through the list.

Should a viewmodel have multiple entities on it?   Or should I really create a ViewModel for each entity, hook all the different viewmodels up to my view or create one master viewmodel that exposes other viewmodels from within, since I have multiple entities that rely on different entities, but all need to be exposed to the user?

Any ideas, suggestions would be much appreciated.

Thanks.


nlm


Bad rendering of PathGeometry?

$
0
0

Hello all. I'm using an Adorner class to draw paths on top of an image displayed in an Image control. I have a series of Point objects that define the path. I'm getting strange rendering in some cases and I'm having trouble pinning down what the cause is. In one case I have two points defined by the coordinates (83,206) and (82,206). I add them to my path figure as follows in my Adorner class:

// Assume "points" contains the two Point objects.

PathFigure pathFigure = new PathFigure();
pathFigure.StartPoint = points[0];

for(Int32 x = 1; x < points.Length; x++)
{
    LineSegment lineSegment = new LineSegment();
    lineSegment.Point = new Point(points[x].X, points[x].Y);
    pathFigure.Segments.Add(lineSegment);
}

pathFigure.IsClosed = true;

PathGeometry pathGeometry = new PathGeometry();
pathGeometry.Figures.Add(pathFigure);

// Render:
drawingContext.DrawGeometry(null, new Pen(Brushes.Red, 1.5), pathGeometry);

When this is rendered to the screen, what should be a very short line instead appears as a line about 8 pxels long that badly overshoots the pixel pair. In other cases, longer paths render properly except at certain locations where the rendered line again appears to overshoot the coordinates by a large margin, sometimes going entirely off of the image control. What on earth is going on here?

Edit: I'm including a screenshot below; the original and the original with the path geometry drawn via the adorner (in red). I'm tracing around the perimeter of white regions using the above method with the geometry defined by an array of Point objects. Everything looks very nice most of the time. The two Point coordinates I discuss above are near the middle of the screen...you can see the line that was drawn looks very strange. These "overshoots" are cropping up elsewhere in the image as well. I've confirmed that my Point arrays contain the proper points, it seems to be how the rendering engine is drawing the closed path. Has anyone seen this before?

WPF: Derive from the ListView or expose Dependency Properties in the base List view control ?

$
0
0

Hi,

I have a custom ListView control with 5 columns. Now, I want exactly the same ListView elsewhere with 2 columns (subset of above) and a different datasource (of course).

Everything else remains the same.

Is it a good practice to add Dependency Properties in the Main ListView for hiding columns and then set those properties from the target usage? If not, then how do I make a derived ListView control from my custom ListView such that I can re-use everything including the XAML and define/override the columns (<GridViewColumn/>) in the derived control's XAML?






Markup extensions at design time not working

$
0
0
  public class DPIAdjustedDouble: global::System.Windows.Markup.MarkupExtension
  {
    public double value { get; set; }

    private static double _factor = 0;

    public DPIAdjustedDouble()
    {
        _factor = 1;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
      return value / _factor;
    }

  }
<cmn:DPIAdjustedDouble value="24" x:Key="DefaultButtonFontSize"></cmn:DPIAdjustedDouble><Style TargetType="{x:Type Button}"><Setter Property="FontSize" Value="{StaticResource DefaultButtonFontSize}" /></Style>

This code does work at runtime, but at design time I get following errors:

  • System.Windows.Markup.XamlParseException
    'DPIAdjustedDouble' is not valid for Setter.Value. The only supported MarkupExtension types are DynamicResourceExtension and BindingBase or derived types.
  • An object of the type "DPIAdjustedDouble" cannot be applied to a property that expects the type "System.Double".

I'm trying to adapt font sizes and other properties to different system font sizes. Originally they were defined as:

<sys:Double value="24" x:Key="DefaultButtonFontSize"></sys:Double>

Scrollviewer Manipulation events blocking button click events

$
0
0

Hi,

I am creating an application which works in desktop and tablet.

I created a user control with 10 Buttons.

In MainWindow, I created a ScrollViewer which has StackPanel as a child.

I have created 5 instance usercontrol and added it into stackpanel.

In scrollviewer, I have set Scrollviewer.PanningMode="None" , IsManipulationEnabled="true"

I have also written ManipulationDelta and ManipulationCompleted events for scrollviewer.

In ManipulationDelta and ManipulationCompleted events, i have written logic to move the scrollviewer page by page nothing but moving one usercontrol at a time.

Now the problem is Button Click events are not triggered. Please help me how activate the button click events.

Please help me.

Note:

I cant make Scrollviewer.PanningMode other than "None" because i want the panning to be done page by page.


Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This will help other members to find the solution easily.

WPF datagrid remove the extra space and extra last column

$
0
0

Hi,

we have a wpf datagrid where dynamically columns are generated,

we are facing an issue while removing the extra space and extra last column in wpf datagrid column.

we also tried setting 'Auto' for all the columns except the last one we set is as '*' , after doing it , whenever the number of columns increases, the horizontal scrollbar as well as column resizing is not working.

need your help in fixing this issue.

Regards

Krishna

How to avoid setting Focus / Tab on Grid ?

$
0
0

Hi,

I have a ListBox inside a normal WPF <Grid/>. When I move around with Arrow keys or Tab, I get the Grid selection (see dotted border around the listbox in the attached image). I tried setting the following in the Grid XAML, but no luck -

KeyboardNavigation.IsTabStop="False"

OR

FocusManager.IsFocusScope="False"

Any idea how to get around this issue ?


How Can I show collection of collection bind to DataGrid?

$
0
0

Hello

I want to group some objects in Data Grid. It works fine. But I want to class properties works as group headers and for rows I want use their List<AntoherClass> variable.

Is that possible?

If doesn’t have to be List<> collection. It can be another collection.

Best Regards

Przemysław Staniszewski


Event Handling of text boxes using MVVM

$
0
0
private void txtUsername_LostFocus(object sender, RoutedEventArgs e)
        {
            string usergrouptxt = txtUsername.Text;
            try
            {
                if (string.IsNullOrEmpty(usergrouptxt))
                {
                    txtUsername.BorderBrush = new SolidColorBrush(Colors.Red);                    
                }
                else
                {
                }
            }
            catch (SqlException usrgrpexc)
            {
                MessageBox.Show(usrgrpexc.ToString());
            }
        }
How can I do the above operation in my ViewModel in MVVM?

Get DataTable row number on CellEditEnding event.

$
0
0

Hi

I have DataGrid which ItemsSource is DataView of DataTable. When CellEditEnding happens on DataGrid I got DataGrid row number.

Row number which is not DataTable row number. So I must use values from DataGrid which are previous value before CellEditEnding ends.

If I understand well I should work on data layer and on this level modify value of columns. But how should I know DataTable rows numer? Should I filter it depending of some item value from DataGridRow?

Best Regards

Przemysław Staniszewski


Drag/drop operations on treeview which is bound to class object in wpf

$
0
0

HI,

Can any one explain how to implement drag and drop operations on tree view whose itemsource is bound to a class object.

How can i scroll the Listbox using the up and down arrow button in wpf without selecting any Listbox Item.?

Persisting state when using Tab Control

$
0
0

 

I have a page with a tabControl consisting of two TabItems : TabItem-1 and TabItem-2. In my TabItem-1 I have a TextBox control (MyTextBox), the content of which I'm TwoWay binding to a business entity's property. Now my textBox uses a template defined in a Style and the style also has a trigger set where if the Validation.HasErrors property is true, change the Template of the TextBox to ErrorTemplate which basically shows an error indicator next to the Textbox Control. Everything works fine so far.

 

Now I have editted the content of MyTextBox to have an invalid data so that the Error indicator shows up next to the control. Next if I go to TabItem-2 and then come back to TabItem-1, the content in the TextBox is the same as what it was before but the error indicator disappeared. It looks like the TextBox is using the default Template rather than the Error Template. Why is this happening the way it is? Is the engine clearing the ErrorCollection for the TextBox control? Is there a way to persist the state of the TabItem?

 

Thanks

Viewing all 18858 articles
Browse latest View live


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