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

Why this binding add 1 extra pixel everytime I move the slider to a tick position?

$
0
0
  private void slider_paragraph_ValueChanged_1(object sender, RoutedPropertyChangedEventArgs<double> e)
        {

            double Ratio = slider_paragraph.Value / (slider_paragraph.Maximum - slider_paragraph.Minimum); // Porcentagem do thumb na tela
            double ThumbPosition = Ratio * slider_paragraph.ActualWidth; //posição absoluta




            rtb1.Focus();

            rtb1.Selection.ApplyPropertyValue(Paragraph.TextIndentProperty, ThumbPosition);

        }

Its ok at first tick. The thumb is aligned with text indent. But after the second one it starts to add 1 pixel everytime I increase the slider value. In the last tick the indentation is about 10 pixels ahead of thumb.

Thanks.


Problem With Rebinding Saved User Control

$
0
0

I am having a problem rebinding a Loaded  WPF User control the target control property does not update , The Control is binding correctly when I first create the control but does not bind After the Control is loaded after being saved. I have understood from a previous post that all Bindings are lost when sterilization takes place. However since I have decided to bind in code I would expect the target to display the source value. Can anyone explain why this is not happening.

UI XAML file  I am only trying to get the lblDescription to display source data at the moment. I  tried multiple ways but none seem to work. The XMLSave function is from code taken from (http://www.codeproject.com/Articles/24681/WPF-Diagram-Designer-Part

<base:BaseUserControl  x:Class="WPFControlLibrary.Controls.HorizontalGauge"
             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:base="clr-namespace:WPFControlLibrary.Base"
             mc:Ignorable="d"
             d:DesignHeight="100" d:DesignWidth="300"><Grid><Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"><Grid.RowDefinitions><RowDefinition Height="25"/><RowDefinition Height="*"/><RowDefinition Height="30"/></Grid.RowDefinitions><Label  Tag="lblDescription"    Content="Not Set" HorizontalAlignment="Center"  Grid.Row="2" VerticalAlignment="Stretch" FontWeight="Bold" FontSize="14"/><Grid Grid.Row="0" HorizontalAlignment="Stretch"  VerticalAlignment="Stretch" ><Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="*"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><Label Tag="lblleftboundary"  Grid.Column="0" Content="{Binding MinValueString}" HorizontalAlignment="Left" FontWeight="Bold"
                      /><Label Tag="lblMiddleBoundary" Grid.Column="1" Content="50" HorizontalAlignment="Center" FontWeight="Bold"/><Label  Tag="lblUpperBoundary"  Grid.Column="2" Content="{Binding MaxValueString}" HorizontalAlignment="Right" FontWeight="Bold"/></Grid><ProgressBar HorizontalAlignment="Stretch" Grid.Row="1"  VerticalAlignment="Stretch" BorderThickness="3" Cursor="Arrow" Foreground="{Binding ProgressBarForground}" Value="{Binding ProgressBarValue}" Background="Black" Maximum="{Binding maxValue}" Minimum="{Binding minValue}" ><ProgressBar.BorderBrush><LinearGradientBrush EndPoint="0,1" StartPoint="0,0"><GradientStop Color="#FFB2B2B2" Offset="0"/><GradientStop Color="#FF5F7A9B" Offset="1"/></LinearGradientBrush></ProgressBar.BorderBrush></ProgressBar></Grid></Grid></base:BaseUserControl>

And here is the Code behind for the Control (only the label bit is important)

using System.Windows.Media;

namespace WPFControlLibrary.Controls
{
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;

    using Dan.monitor.Common;

    using WPFControlLibrary.Base;



    [MonitorControl(true)]

    public partial class HorizontalGauge : BaseUserControl, IMonitorControl
    {
        private ProgressBar hProgressBar;
        private Dictionary<string, Label> labels = new Dictionary<string, Label>();
        private float _progressBarValue;
        private SolidColorBrush progressBarForground;
        public HorizontalGauge()
        {
            InitializeComponent();
            RebindControls();
            NewValueReceived+=HorizontalGauge_NewValueReceived;
        }


        private void RebindControls()
        {
            var grid = this.FindChild<Grid>();
            hProgressBar = this.FindChild<ProgressBar>();
            foreach (var child in grid.FindChildren<Label>(x=> !string.IsNullOrEmpty(x.Tag.ToString())))
            {
                labels.Add(child.Tag.ToString(),child);
            }

            Binding descriptionBinding = new Binding("Description");
            descriptionBinding.Source = this;
            descriptionBinding.Mode = BindingMode.OneWay;
            BindingOperations.SetBinding(labels["lblDescription"], Label.ContentProperty, descriptionBinding);
        }

        private void HorizontalGauge_NewValueReceived(NewMetricEventValue e)
        {
            if (e.Value != null)
            {
                ProgressBarValue = (float)e.Value.Raw;
            }
        }

        public float ProgressBarValue
        {
            get
            {
                return this._progressBarValue;
            }
            set
            {
                this._progressBarValue = value;
                CheckColorStatus(value);
                this.CallPropertyChange("ProgressBarValue");
            }
        }

        public SolidColorBrush ProgressBarForground
        {
            get
            {
                return this.progressBarForground;
            }
            set
            {
                if (this.progressBarForground != value) this.progressBarForground = value;
                this.CallPropertyChange("ProgressBarForground");
            }
        }

        private void CheckColorStatus(float value)
        {
                if (value <= Ok)
                {
                    ProgressBarForground = new SolidColorBrush(OkColor);
                }

                if (value > Warn)
                {
                    ProgressBarForground = new SolidColorBrush(WarnColor);
                }
                if (value >= Alert)
                {
                    ProgressBarForground = new SolidColorBrush(AlertColor);
                }
        }
    }
}

And Here is the BaseClass (Reduced)

// --------------------------------------------------------------------------------------------------------------------
//
//
// </copyright>
// <summary>
//   The base user control.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace WPFControlLibrary.Base
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Media;

    using Dan.monitor.Common;
    using Dan.monitor.Common.Dan.Common.Messages;

    /// <summary>
    /// The base user control.
    /// </summary>
    public abstract class BaseUserControl : UserControl, INotifyPropertyChanged
    {
        private float alert;

        private Color alertColor;

        private string description;

        private bool emailOnAlert;

        private EmailMessage emailReceipient;

        private IMetricValue value;

        private string monitoringEvent;

        private float ok;

        private Color okColor;

        private float warn;

        private Color warnColor;

        private bool autoMin;

        private bool autoMax;

        private float maxValue;

        private float minValue;

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="BaseUserControl"/> class.
        /// </summary>
        public BaseUserControl()
        {
            this.MouseDoubleClick += this.UserControl_MouseDoubleClick;
        }

        #endregion

        #region Public Events

        /// <summary>
        /// The double clicked.
        /// </summary>
        public event EventHandler DoubleClicked;

        #endregion

        #region Public Properties

        /// <summary>
        /// Gets or sets the alert.
        /// </summary>
        public float Alert
        {
            get
            {
                return this.alert;
            }
            set
            {
                this.alert = value;
            }
        }

        /// <summary>
        /// Gets or sets the alert color.
        /// </summary>
        public Color AlertColor
        {
            get
            {
                return this.alertColor;
            }
            set
            {
                this.alertColor = value;
            }
        }

        /// <summary>
        /// Gets or sets the description.
        /// </summary>
        public  string Description
        {
            get
            {
                return this.description;
            }
            set
            {
                if (this.description != value)
                {
                    this.description = value;
                    PropertyChanged(this, new PropertyChangedEventArgs("Description"));
                }
            }

        }

        /// <summary>
        /// Gets or sets a value indicating whether email on alert.
        /// </summary>
        public virtual bool EmailOnAlert
        {
            get
            {
                return this.emailOnAlert;
            }
            set
            {
                this.emailOnAlert = value;
            }
        }

        /// <summary>
        /// Gets or sets the email receipient.
        /// </summary>
        public virtual EmailMessage EmailReceipient
        {
            get
            {
                return this.emailReceipient;
            }
            set
            {
                this.emailReceipient = value;
            }
        }

        public virtual IMetricValue Value
        {
            get
            {
                return this.value;
            }
            set
            {
                this.value = value;
                NewValueReceived(new NewMetricEventValue(value));

            }
        }

        /// <summary>
        /// Gets or sets the monitoring event.
        /// </summary>
        public string MonitoringEvent
        {
            get
            {
                return this.monitoringEvent;
            }
            set
            {
                this.monitoringEvent = value;
            }
        }

        /// <summary>
        /// Gets or sets the ok.
        /// </summary>
        public virtual float Ok
        {
            get
            {
                return this.ok;
            }
            set
            {
                this.ok = value;
            }
        }

        /// <summary>
        /// Gets or sets the ok color.
        /// </summary>
        public virtual Color OkColor
        {
            get
            {
                return this.okColor;
            }
            set
            {
                this.okColor = value;
            }
        }

        /// <summary>
        /// Gets or sets the warn.
        /// </summary>
        public virtual float Warn
        {
            get
            {
                return this.warn;
            }
            set
            {
                this.warn = value;
            }
        }

        /// <summary>
        /// Gets or sets the warn color.
        /// </summary>
        public virtual Color WarnColor
        {
            get
            {
                return this.warnColor;
            }
            set
            {
                this.warnColor = value;
            }
        }

        public virtual bool AutoMin
        {
            get
            {
                return this.autoMin;
            }
            set
            {
                this.autoMin = value;
            }
        }

        public virtual bool AutoMax
        {
            get
            {
                return this.autoMax;
            }
            set
            {
                this.autoMax = value;
            }
        }

        public virtual float MaxValue
        {
            get
            {
                return this.maxValue;
            }
            set
            {
                this.maxValue = value;
                MaxValueString = value.ToString();
                PropertyChanged(this, new PropertyChangedEventArgs("maxValue"));
            }
        }

        public virtual float MinValue
        {
            get
            {
                return this.minValue;
            }
            set
            {
                this.minValue = value;
                MinValueString = value.ToString();
                PropertyChanged(this, new PropertyChangedEventArgs("minValue"));
            }
        }

        public string MinValueString
        {
            get
            {
                return this.minValueString;
            }
            set
            {
                this.minValueString = value;
                PropertyChanged(this, new PropertyChangedEventArgs("MinValueString"));
            }
        }


        public string MaxValueString
        {
            get
            {
                return this.maxValueString;
            }
            set
            {
                this.maxValueString = value;
                PropertyChanged(this, new PropertyChangedEventArgs("MaxValueString"));
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// The user control_ mouse double click.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="e">
        /// The e.
        /// </param>
        private void UserControl_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.DoubleClicked(sender, e);
        }

        #endregion

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        public delegate void NewValueReceivedEventHandler(NewMetricEventValue e);
        public event NewValueReceivedEventHandler NewValueReceived = delegate { };

        private string minValueString;
        private string maxValueString;


        void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }


        internal void CallPropertyChange(string propertyName)
        {
            PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
        }
    }

    public class NewMetricEventValue
    {
        public IMetricValue Value;
        public NewMetricEventValue(IMetricValue e)
        {
            Value = e;

        }
    }


}


Developer of bits

my UserControl with ItemsControl and DataTemplate does not display in MainWindow -- how to fix?

$
0
0

I put together a sample WPF mvvm project (in VS2012) from a video tutorial on ItemsControl usage (no source code available for download).  In the video the MainWindow displays data from the UserControl which contains the ItemsControl, DataTemplate, ... it displays three rows of data (Employee Names, firstname, lastname).  My project runs but the MainWindow does not show the UserControl window.  One thing that is interesting about this project is that in the video the UserControl performs some kind of looping style behavior that displays 3 rows of textboxes (there is only one FirstName Textbox and only one LastName Textbox in the xaml).  Obviously, I'm missing something in my project -- maybe the video didn't show something or maybe I just overlooked something (maybe I need an additional reference to some ExpressionBlend assembly?), maybe I misspelled something?.  I am hoping that a look at the code below  maybe someone can see what is missing.  The objects appear to populate correctly in my source code when I step through it in Debug mode. My sample project source can be downloaded

here

The project contains a DataAccess folder with EmployeeRepository.cs -- this is the mock database file with three employees.

Then there is the Model folder wtih Employee.cs which contains a CreateEmployee method

There is a View folder which contains EmployeeListView.xaml -- the UserControl which contains the ItemsControl and DataTemplate ...

The ViewModel folder contains three viewmodel files -- EmployeeListViewModel.cs, MainWindowViewModel.cs, ViewModelBase.cs

and MainWindow.xaml in the root folder.

The DataContext is set in App.xaml.cs

Here is the MainWindow running -- from my project

Here is the MainWindow from the video -- this is what it is supposed to look like

Here is my project layout in VS2012 -- the same as in the video

Here is the project source code - that I visually copied from the video

MainWindow.xaml

<Window x:Class="myWpfDataExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:myWpfDataExample.ViewModel"
        xmlns:vw="clr-namespace:myWpfDataExample.View"
        Title="MainWindow" Height="350" Width="525"><Window.Resources><DataTemplate DataType="{x:Type vm:EmployeeListViewModel}" ><vw:EmployeeListView /></DataTemplate></Window.Resources><Grid Margin="4"><Border Background="GhostWhite" BorderBrush="LightGray" BorderThickness="1" CornerRadius="5"><ItemsControl ItemsSource="{Binding viewModels}" Margin="4" /></Border></Grid></Window>

EmployeeListView.xaml -- this is what I believe I saw from the video.  AllEmployees (binding) is contained in EmployeeListViewModel.cs

<UserControl x:Class="myWpfDataExample.View.EmployeeListView"
             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"
             d:DesignHeight="300" d:DesignWidth="500" ><StackPanel><Label Content="testing"/><ItemsControl ItemsSource="{Binding AllEmployees}"><ItemsControl.ItemTemplate><DataTemplate><StackPanel Orientation="Horizontal"><TextBox Width="100" Text="{Binding FirstName}" /><TextBox Width="100" Text="{Binding LastName}" /></StackPanel></DataTemplate></ItemsControl.ItemTemplate></ItemsControl></StackPanel></UserControl>

EmployeeRepository.cs - the mock database with the Employee Data

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using myWpfDataExample.Model;

namespace myWpfDataExample.DataAccess
{
    public class EmployeeRepository
    {
        readonly List<Employee> _employees;

        public EmployeeRepository()
        {
            if (_employees == null)
            {
                _employees = new List<Employee>();
            }

            _employees.Add(Employee.CreateEmployee("John", "Smith"));
            _employees.Add(Employee.CreateEmployee("Jill", "Jones"));
            _employees.Add(Employee.CreateEmployee("Cathy", "Mortz"));
        }

        public List<Employee> GetEmployees()
        {
            return new List<Employee>(_employees);
        }
    }
}

Employee.cs -- the Model

namespace myWpfDataExample.Model
{
    public class Employee
    {
        public static Employee CreateEmployee(string firstName, string lastName)
        {
            return new Employee { FirstName = firstName, LastName = lastName };
        }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }
}

EmployeeListViewModel.cs

using System;
using System.Collections.ObjectModel;
using myWpfDataExample.DataAccess;

namespace myWpfDataExample.ViewModel
{
    class EmployeeListViewModel : ViewModelBase
    {
        readonly EmployeeRepository _employeeRepository;

        public ObservableCollection<Model.Employee> AllEmployees
        {
            get;
            private set;
        }

        public EmployeeListViewModel(EmployeeRepository employeeRepository)
        {
            if (employeeRepository == null)
            {
                throw new ArgumentNullException("employeeRepository");
            }

            _employeeRepository = employeeRepository;
            this.AllEmployees = new ObservableCollection<Model.Employee>(_employeeRepository.GetEmployees());
            Console.WriteLine(this.AllEmployees.Count);
            Console.WriteLine();
        }

        protected override void OnDispose()
        {
            this.AllEmployees.Clear();
        }
    }
}

MainWindowViewModel.cs

using System.Collections.ObjectModel;
using myWpfDataExample.DataAccess;
using System;

namespace myWpfDataExample.ViewModel
{
    //--source of project;  https://www.youtube.com/watch?v=PUvZ5wVrZ4s
    public class MainWindowViewModel : ViewModelBase
    {
        EmployeeRepository _employeeRepository;
        ObservableCollection<ViewModelBase> _viewModels;

        public MainWindowViewModel()
        {
            _employeeRepository = new EmployeeRepository();
            EmployeeListViewModel viewModel = new EmployeeListViewModel(_employeeRepository);
            this.ViewModels.Add(viewModel);
        }

        public ObservableCollection<ViewModelBase> ViewModels
        {
            get
            {
                if (_viewModels == null)
                {
                    _viewModels = new ObservableCollection<ViewModelBase>();
                }

                return _viewModels;
            }
        }
    }
}

ViewModelBase.cs

using System;
using System.ComponentModel;

namespace myWpfDataExample.ViewModel
{
    public class ViewModelBase : INotifyPropertyChanged, IDisposable
    {
        protected ViewModelBase()
        {
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string PropertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(PropertyName);
                handler(this, e);

            }
        }

        public void Dispose()
        {
            this.OnDispose();
        }

        protected virtual void OnDispose()
        {
        }
    }
}

App.xaml.cs -- MainWindow.xaml gets loaded from here and not from App.xaml

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using myWpfDataExample.ViewModel;

namespace myWpfDataExample
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            MainWindow window = new MainWindow();
            var viewModel = new MainWindowViewModel();
            window.DataContext = viewModel;
            window.Show();
        }
    }
}


Rich P








Edmx file T4 vs ObjectContext inherited

$
0
0

Hello,

Today i'm trying to create new model with property "strategy generate code" set toObjectContext inherited.

My probleme is when i make right-click and use generate database from model, my model automatically change to T4 and generate T4 model...

How can i change this ? Why i can't use it ?

I use Visual Studio 2013.

I'm working with sql Express

WPF desktop application without Visual Studio

$
0
0

How to create WPF desktop app without using visual studio?

I have installed only .NET Framework 4.5, Is it possible to do it?

Any help would be greatly appreciated!!

Datagrid: Can I set a tranparency level for column background color?

$
0
0

Hi all,

I have a datagrid with background colors set using triggers. This works. I would like to set a column background color but I don't want to make the color solid because it will block the row color. Is there a way to set the column background color transparency to 50% (or less) so that I can still see (or blend) with the row background color? I can set the "background" property of the column to a value of "transparent" but this makes no sense without a color.

Thanks

<DataGrid.RowStyle><Style TargetType="DataGridRow"><Style.Triggers><DataTrigger Binding="{Binding col_oPutorCall}" Value="call"><Setter Property="Background" Value="Cornsilk"/></DataTrigger><DataTrigger Binding="{Binding col_oPutorCall}" Value="put"><Setter Property="Background" Value="BlanchedAlmond"/></DataTrigger><DataTrigger Binding="{Binding col_rowColor}" Value="false"><Setter Property="Background" Value="LightGreen"/></DataTrigger></Style.Triggers></Style></DataGrid.RowStyle>

<DataGridTextColumn Binding="{Binding col_oBid, StringFormat=F2}" FontFamily="Arial" FontWeight="Bold" FontSize="12" Header="oB" ><DataGridTextColumn.CellStyle><Style TargetType="DataGridCell"><Setter Property="Background" Value= "Transparent" /><Setter Property="Background" Value= "AliceBlue" /></Style></DataGridTextColumn.CellStyle></DataGridTextColumn>

Getting command line output dynamically

$
0
0

I am executing one command line argument through WPF application but not getting any output of command line execution. But if I will execute same command through command line manually then getting out put. I am using synchronous operation and below code.

System.Diagnostics.ProcessStartInfo procStartInfo =
                    new System.Diagnostics.ProcessStartInfo("cmd", "/C " + commandlinearg);

procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
procStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
procStartInfo.WorkingDirectory = strToolsPath;           
procStartInfo.RedirectStandardOutput = true;

System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;

proc.Start();

result = proc.StandardOutput.ReadToEnd();

proc.Close();

--Mrutyunjaya

Horizontal text positioning of DrawString method

$
0
0

I am trying to reproduce the below XPS XAML using the GDI+:

<FixedPage xmlns="http://schemas.microsoft.com/xps/2005/06" xmlns:x="http://schemas.microsoft.com/xps/2005/06/resourcedictionary-key" xml:lang="und" Width="816" Height="1056">

      <Path Fill="#FFFFFFFF" Data="M0,0L816,0 816,1056 0,1056Z" />

             <Canvas Clip="M0,0L816,0 816,1056 0,1056Z">

                    <Path Fill="#FFFFFFFF" Data="M0,0L816,0 816,1056 0,1056Z" />

                    <Path Fill="#FF008000" Data="M0,0L816,0 816,1056 0,1056Z" />

                    <Canvas RenderTransform="1,0,0,1,10,10">

                          <Path Fill="#FFFFFF00" Data="M0,0L796,0 796,120 0,120Z" />

                          <Canvas Clip="M0,0L796,0 796,120 0,120Z">

                                 <Glyphs OriginX="0" OriginY="87.5866666666667" FontRenderingEmSize="96" FontUri="/Resources/1057478c-ad6c-46da-af29-3e00c349c111.ODTTF" UnicodeString="Rutger Koperdraad" Fill="#FF000000" xml:lang="en-us" />

                          </Canvas>

                    </Canvas>

      </Canvas>

</FixedPage>

I manage to get the rectangles and the vertical text position correctly printed to the XPS document writer using the code below:

   PrivateSub OnPrintPageEx(senderAsObject, e AsPrintPageEventArgs)

       If m_intPageNumber < m_objPaginator.PageCountThen

           Using objGraphics As System.Drawing.Graphics = e.Graphics

               ' Correction factor between WPF and printer units

               Dim f As Single = 100 / 96

               ' Set the graphics quality

               objGraphics.SmoothingMode = Drawing.Drawing2D.SmoothingMode.None

               objGraphics.InterpolationMode = Drawing.Drawing2D.InterpolationMode.NearestNeighbor

               ' Draw the green background

               Dim stcRect1 AsNew Drawing.RectangleF(0, 0, 816 * f, 1056 * f)

               Call objGraphics.FillRectangle(Drawing.Brushes.DarkGreen, stcRect1)

               ' Draw the yellow rectangle

               Dim stcRect2 AsNew Drawing.RectangleF(0, 0, 796 * f, 120 * f)

               Call objGraphics.TranslateTransform(10 * f, 10 * f)

               Call objGraphics.FillRectangle(Drawing.Brushes.Yellow, stcRect2)

               ' Draw the text

               Dim objFont AsNew Drawing.Font("Times New Roman", 72)

               Dim intEmHeight AsInteger = objFont.FontFamily.GetEmHeight(objFont.Style)

               Dim intCellAscent AsInteger = objFont.FontFamily.GetCellAscent(objFont.Style)

               Dim sngOffset AsSingle = 87.58667F - 96.0F / intEmHeight * intCellAscent

               Dim stcRect3 AsNew Drawing.RectangleF(0, sngOffset * f, 796 * f, 120 * f)

               Call stcRect3.Inflate(100 / 96, 100 / 96)

               Call objGraphics.DrawString("Rutger Koperdraad", objFont, Drawing.Brushes.Black, stcRect3)

           EndUsing

           m_intPageNumber += 1

           e.HasMorePages = (m_intPageNumber < m_objPaginator.PageCount)

       EndIf

   EndSub

However, the horizontal text positioning is still different. The first letter starts too far to the right and the overall text is wider. How can I reproduce the XAML correctly in the GDI+?

To give some background: I have a WPF application that can print using WPF/XPS technology. Since this print path gives quality problems on many legacy printer driver (bad image resolution due to a bug in the XPS to GDI+ conversion), I am building an alternative print engine based on the GDI+. So effectively, I need to convert my WPF graphics to the GDI+.


Rutger Koperdraad.


Thousands Separator issue

$
0
0

hello

i've ListBox Itemtemplate with LABEL.

the label contains an amount Ex: 12345677, I would like it appears like 12,345,677

I've tried this

<Label      Content="{Binding BaseSalary, StringFormat={0:n}}" FontSize="13"   HorizontalAlignment="Stretch"  Foreground="{DynamicResource colorTitlebox}"    HorizontalContentAlignment="Right"   />

this also change nothing.

<Label      Content="{Binding BaseSalary, StringFormat='0,0'}" FontSize="13"   HorizontalAlignment="Stretch"  Foreground="{DynamicResource colorTitlebox}"    HorizontalContentAlignment="Right"   />

this method too 

where is my mistake please ???

How to solve text wrapping problem in grid

$
0
0

I have create a simple ui with grid  and contains a long paragraph text. However the text will not break line to another paragraph and expand the UI width.

BView.xaml

<UserControl x:Class="SimpleUI.Views.BView"
             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:resources="clr-namespace:SimpleUI.Properties"
             xmlns:view="clr-namespace:SimpleUI.Views"
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"><Grid><Grid.RowDefinitions><RowDefinition Height="Auto" /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="Auto" /><ColumnDefinition Width="5" /><ColumnDefinition Width="Auto" /></Grid.ColumnDefinitions><GroupBox Grid.Column="0" Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Header="{x:Static resources:Resources.Course}"><Grid><Grid.RowDefinitions><RowDefinition Height="10" /><RowDefinition Height="Auto" /><RowDefinition Height="10" /><RowDefinition Height="Auto" /><RowDefinition Height="10" /><RowDefinition Height="Auto" /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width=".2*"/><ColumnDefinition Width="2" /><ColumnDefinition Width=".2*"/><ColumnDefinition Width="2" /><ColumnDefinition Width=".2*"/><ColumnDefinition Width="2" /></Grid.ColumnDefinitions><UniformGrid Grid.Column="0" Grid.Row="1" Columns="2" Grid.ColumnSpan="6" HorizontalAlignment="Center" VerticalAlignment="Center"><RadioButton Margin="0, 0, 10, 0" GroupName="ClassType" Content="{x:Static resources:Resources.ClassA}" /><RadioButton Margin="0, 0, 10, 0" GroupName="ClassType" Content="{x:Static resources:Resources.ClassB}" /></UniformGrid><Border Grid.Column="0" Grid.Row="3" Grid.ColumnSpan="6" BorderThickness="1" Padding="9" BorderBrush="LightGray"><Grid><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="10" /><RowDefinition Height="Auto"/><RowDefinition Height="10" /><RowDefinition Height="Auto"/><RowDefinition Height="2" /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width=".3*" /><ColumnDefinition Width="10"/><ColumnDefinition Width=".25*" /><ColumnDefinition Width="10"/><ColumnDefinition Width=".25*" /></Grid.ColumnDefinitions><TextBlock Grid.Column="0" Grid.Row="0" Text="{x:Static resources:Resources.MaterialA}" /><TextBox Grid.Column="2" Grid.Row="0" Width="120" /><ComboBox Grid.Column="4" Grid.Row="0" Width="120"/><TextBlock Grid.Column="0" Grid.Row="2" Text="{x:Static resources:Resources.MaterialB}" /><TextBox Grid.Column="2" Grid.Row="2" Width="120" /><ComboBox Grid.Column="4" Grid.Row="2" Width="120" /><TextBlock Grid.Column="0" Grid.Row="4" Text="{x:Static resources:Resources.MaterialC}" /><TextBox Grid.Column="2" Grid.Row="4" Width="120" /><ComboBox Grid.Column="4" Grid.Row="4" Width="120" /></Grid></Border><view:MessageView Grid.Column="0" Grid.Row="5" /></Grid></GroupBox></Grid></UserControl>

MessageView.xaml
<UserControl x:Class="SimpleUI.Views.MessageView"
             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:resources="clr-namespace:SimpleUI.Properties"
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"><Grid><Grid.RowDefinitions><RowDefinition Height="Auto" /><RowDefinition Height="10" /><RowDefinition Height="Auto" /></Grid.RowDefinitions><TextBlock Grid.Row="0" Text="{x:Static resources:Resources.Error}" TextTrimming="None" FontWeight="UltraBold" /><TextBlock Grid.Row="2" Text="{x:Static resources:Resources.ErrorDescription}" TextAlignment="Justify" TextWrapping="Wrap"  VerticalAlignment="Center" /></Grid></UserControl>

MainWindow.xaml

<UserControl x:Class="SimpleUI.Views.MessageView"
             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:resources="clr-namespace:SimpleUI.Properties"
             mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"><Grid><Grid.RowDefinitions><RowDefinition Height="Auto" /><RowDefinition Height="10" /><RowDefinition Height="Auto" /></Grid.RowDefinitions><TextBlock Grid.Row="0" Text="{x:Static resources:Resources.Error}" TextTrimming="None" FontWeight="UltraBold" /><TextBlock Grid.Row="2" Text="{x:Static resources:Resources.ErrorDescription}" TextAlignment="Justify" TextWrapping="Wrap"  VerticalAlignment="Center" /></Grid></UserControl>



Target Result


Download Sample Project



WPF Mutex Blocks UI Thread c#

$
0
0

HI,

I have background thread in my application which uses mutex like this:

      void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
          MyMutex.MuImageLock.WaitOne();                
          foreach (var file in ImageFiles)
          {
              SyncFileToLocalImage(file.FileNameNoPath);
          }
           MyMutex.MuImageLock.ReleaseMutex();          
        }
and it takes around several min (2-3) min to sync. Now there is one more background thread in my application which do same thing just to make sure.

My Issue is, before I start my 2nd thread I want to check that if mutex is available or not. If it's not available that means another thread is running, then I do not need to start this new thread. so to check that I a using below code. 

But using below code, WaitOne method blocks my UI thread until that previous thread does not release Mutex. 

    if (MyMutex.MuImageLock.WaitOne())
    {
       getPRImages();
       MyMutex.MuImageLock.ReleaseMutex();
    }

I dont want to block my current UI thread I just want to see that mutex is available or not. How would I do that?

Thanks
Dee


Datagrid: Setting column background color removes the cell padding?

$
0
0

Hi all,

I have a datagrid with row colors. In another post I got how to set a column color semi-transparent using a grid.resource. The problem is that when I set the column color the padding for that column goes away. It doesn't matter if I use a grid.resource or I set the column background color directly under the datagridtextcolumn in the xml, the column padding is gone (see pictures pls.). I've included the pertinent code below. How do I prevent the padding from going away with the column color set?

Thanks

Without column background color:

with column background color:

<Grid.Resources><SolidColorBrush x:Key="oBidHighlight" Color="Orange" Opacity=".3" /></Grid.Resources><DataGrid x:Name="optionsDataDatagrid" Margin="0,10" Grid.Column="1" FontFamily="Arial" FontSize="13" HorizontalAlignment="Stretch" CanUserSortColumns="False" CanUserReorderColumns="False" AutoGenerateColumns="False" HorizontalGridLinesBrush="LightGray" VerticalGridLinesBrush="LightGray" FontWeight="Bold" IsReadOnly="True" SelectionMode="Single" SelectionUnit="Cell" CanUserResizeRows="False" RowHeaderWidth="0" HeadersVisibility="Column" MouseDown="optionsDataDatagrid_MouseDown"><DataGrid.RowStyle><Style TargetType="DataGridRow"><Style.Triggers><DataTrigger Binding="{Binding col_oPutorCall}" Value="call"><Setter Property="Background" Value="Cornsilk"/></DataTrigger><DataTrigger Binding="{Binding col_oPutorCall}" Value="put"><Setter Property="Background" Value="BlanchedAlmond"/></DataTrigger><DataTrigger Binding="{Binding col_rowColor}" Value="false"><Setter Property="Background" Value="LightGreen"/></DataTrigger></Style.Triggers></Style></DataGrid.RowStyle><DataGrid.ColumnHeaderStyle><Style TargetType="DataGridColumnHeader"><Setter Property="HorizontalAlignment" Value="Stretch" /><Setter Property="HorizontalContentAlignment" Value="Center" /></Style></DataGrid.ColumnHeaderStyle><DataGrid.CellStyle><Style TargetType="DataGridCell" ><Setter Property="TextBlock.TextAlignment" Value="Center" /><Setter Property="Padding" Value="10,2,10,2"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type DataGridCell}"><Border Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"><ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" /></Border></ControlTemplate></Setter.Value></Setter></Style></DataGrid.CellStyle><DataGrid.Columns><DataGridTextColumn Binding="{Binding col_sBid, StringFormat=F2}" FontFamily="Arial" FontWeight="Normal" FontSize="12" Header="sB" /><DataGridTextColumn Binding="{Binding col_sAsk, StringFormat=F2}" FontFamily="Arial" FontWeight="Normal" FontSize="12" Header="sA" /><DataGridTextColumn Binding="{Binding col_sVolume, StringFormat=N0}" FontFamily="Arial" FontWeight="Normal" FontSize="12" Header="sVol" /><DataGridTextColumn Binding="{Binding col_datetime, StringFormat=MM/dd/yy hh:mm:ss tt}" FontFamily="Arial" FontWeight="Normal" FontSize="12" Header="Date" /><DataGridTextColumn Binding="{Binding col_oBid, StringFormat=F2}" FontFamily="Arial" FontWeight="Bold" FontSize="12" Header="oB" ><!--  <DataGridTextColumn.CellStyle><Style TargetType="DataGridCell"><Setter Property="Background" Value="{StaticResource oBidHighlight}" /></Style></DataGridTextColumn.CellStyle>
                    --></DataGridTextColumn><DataGridTextColumn Binding="{Binding col_oAsk, StringFormat=F2}" FontFamily="Arial" FontWeight="Bold" FontSize="12" Header="oA" /><DataGridTextColumn Binding="{Binding col_oOpenInterest, StringFormat=N0}" FontFamily="Arial" FontWeight="Normal" FontSize="12" Header="OI" /><DataGridTextColumn Binding="{Binding col_oDaysToExpiration}" FontFamily="Arial" FontWeight="Normal" FontSize="12" Header="XD" /><DataGridTextColumn Binding="{Binding col_oLow, StringFormat=F2}" FontFamily="Arial" FontWeight="Normal" FontSize="12" Header="oL" /><DataGridTextColumn Binding="{Binding col_oHigh, StringFormat=F2}" FontFamily="Arial" FontWeight="Normal" FontSize="12" Header="oH" /><DataGridTextColumn Binding="{Binding col_oVolume, StringFormat=N0}" FontFamily="Arial" FontWeight="Normal" FontSize="12" Header="oVol" /></DataGrid.Columns></DataGrid>

Updating the binding property when loading data from a saved file?

$
0
0
<TextBox x:Name="odTxtbox" Text="{Binding DoOrID,NotifyOnSourceUpdated=True,UpdateSourceTrigger=PropertyChanged}" Grid.Row="2" Grid.Column="1"/>

I know if I use UpdateSourceTrigger=PropertyChanged, it'll work!

I have saved control's values (eg TextBox) into a text file and retrieve it like this:

                foreach (TextBox tb in window.FindChildren<TextBox>())
                {
                    tb.Text = inputs[i];
                    i++;
                }

But when loading the values back to controls it doesn't update. 

The reason why I am reluctant to use "UpdateSourceTrigger=PropertyChanged" is because I only need it when loading the information from a text file.

Ladder and snake game

$
0
0

hi, iam making a ladder and snake game in c# for windows application.

i have to ask about this game,firstly i want to move an image from one place to another.like when i roll a dice and 4 random number appear on a dice and my piece is placed on 2.when i press a button,my piece should move on 6th position but how can i do this.

here is a code given below but this what its do,its display a random numer

private void button1_Click(object sender, RoutedEventArgs e)
        {
            Random num = new Random();
            int Number = num.Next(1, 7);
            BitmapImage Img = new BitmapImage(new Uri("ms-appx:///DiceFaces/" + Number.ToString() + ".png"));
            textBlock1.Text = Number.ToString() + " Number"; 
            image1.Source = Img;
        }

now how can i move an image on a board.please help me

thanks in advance


Rabia (Microsoft Student Partner)

Problem with Checklist box control

$
0
0

Hello everyone,

I am using VS2008 and i added a checklist box control in wpf project and the checklistbox control also added successfully,but the problem is that when i am going to add checklistboxitem inside checklistbox then in intelisece not showing that property so how can i add the checklistbox item inside it.

Second thing when i am going to add other control for eg: checkbox then it successfully added but it showing two checkbox for one checkbox control, so can any one help me how to solve this and add checklistbox item inside it.

Note:I already added wpftoolkit.extended dll in my WPF project  


S.K Nayak



Cannot convert Office2013ResourceKey to MarkupExtension while serializing Xaml document

$
0
0
Hello,

I have a trouble Saving a resource dictionary which uses Telerik.Windows.Controls assembly. Telerik.Windows.Controls.

The exception thrown:

An unhandled exception of type 'System.NotSupportedException' occurred in System.dll

Additional information: 'Office2013ResourceKeyTypeConverter' is unable to convert 'Telerik.Windows.Controls.Office2013ResourceKey' to 'System.Windows.Markup.MarkupExtension'.

Part of xaml that's causing the problem:

<Grid>                <Path                    Stretch="Fill"                    Fill="{telerik1:Office2013Resource ResourceKey=ValidationBrush}"                    HorizontalAlignment="Left"                    VerticalAlignment="Top"                    SnapsToDevicePixels="True"/>                <Border Background="{telerik1:Office2013Resource
ResourceKey=ValidationBrush}" Margin="5 0 0 0" Padding="1">                    <ContentPresenter                        Content="{Binding Error}"                        TextBlock.Foreground="{telerik1:Office2013Resource ResourceKey=MainBrush}"                        Margin="4 2"                        TextBlock.FontSize="15"                         />                </Border>            </Grid>            <ContentControl/>        </Grid>

and namespace mapping:

xmlns:telerik1="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls"

I load this resource dictionary with

var myDict = Application.LoadComponent(new Uri(packUri, UriKind.Relative)) as ResourceDictionary;
and then try to save it with:

System.Windows.Markup.XamlWriter.Save(myDict);

And that's when the exception is thrown.

Compiler tooltip: "Local property 'ResourceKey' can only be applied to types that are derived from ThemeResourceExtension`1"

I've checked it, and Office2013ResourceExtension derives from ThemeResourceExtension`1.

What might be the problem here?

How to get the visual elements of diffrent visualTrees(hosted in one sample)?

$
0
0

Hi,

We have hosted two different controls in WPF Sample.

While moving the Mouse one to another , need to find the Visual elements based on the Position.

Is that possible with VisualHit?

Regards,

Ramya

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

how to make a unbound datagrid (wpf) with custom columns

$
0
0

I need to create a flex grid where I have to show different Items on a single cell (one or more button, some label). The number of item can change on different cells so is not possible to create a predefined data source. So I am looking how to setup a simple usecontrol that can accomodate the button and use this as column template.

I have two question:

1)how can I make the usercontrol able to grow up as the number of button increase and how can I make the datagrid row height "autosize" to accomodate the usercontrol and show all the content

2) how can I add a empty row on the datagrid and access a single cell (and the usercontrol) to set and read its property.

I've also tried to do this using a simple wpf grid but its miss many things (head and row fixed header, visible grid) 

Thank you

Alessandro


alex

Creating a non UI class in WPF that can have RoutedEvents

$
0
0

I have a WPF app written in VS 2010 C#. I have written a class that is not a user interface element (not a window, control, usercontrol... just a class that does stuff). I would like to have this class host RoutedEvents. However, when I insert the following code:

        public event RoutedEventHandler Custom
        {
            add
            {
                AddHandler(CustomEvent, value);
            }
            remove
            {
                RemoveHandler(CustomEvent, value);
            }
        }

        protected void OnCustom()
        {
            RaiseEvent(new RoutedEventArgs(CustomEvent, this));

        }

AddHandler, RemoveHandler and RaiseEvent  have errors because "The name 'xxxxHandler' does not exist in the current context".

Of course if I derived my class from something like UserControl, the errors would not be there. So, is it possible to get my class to be able to host a RoutedEvent and if so, what must I derive from or modify?

Michael


Michael
Viewing all 18858 articles
Browse latest View live


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