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

How can I get my picture scroll horzontally

$
0
0

Dear all,

I have the follwoing layout in my application:

<Grid x:Name="_mainGrid" Background="#cfd8dc" ><Grid.RowDefinitions><RowDefinition Height="80"/><RowDefinition Height="*"/><RowDefinition Height="80"/></Grid.RowDefinitions><!--Display header information--><Border Background="{StaticResource PS_Headerbrush}"><Grid><StackPanel Orientation="Horizontal" Grid.ColumnSpan="2" HorizontalAlignment="Left" Padding="10" VerticalAlignment="Center" ><TextBlock Text="{Binding SelectedProduct.ProductName,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" Style="{StaticResource  HeaderTextStyle}"/></StackPanel><StackPanel Orientation="Horizontal" Grid.ColumnSpan="2" HorizontalAlignment="Right" Padding="10" VerticalAlignment="Center" ><TextBlock x:Uid="lblRef"  Style="{StaticResource HeaderTextStyle}"/><TextBlock Text="{Binding SelectedProduct.ProductCode,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" Style="{StaticResource HeaderTextStyle}"/><SymbolIcon Margin="15,0,0,0"  Symbol="Favorite" Foreground="White" Visibility="{Binding IsFavoriteProduct,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource VisibilityConverter}}"/></StackPanel></Grid></Border><GridView x:Name="_grPictures" Grid.Row="1"
							  ItemsSource="{Binding SelectedProduct.ProductPictures}"
							  ItemTemplate="{StaticResource PictureTemplate}"
								SelectionMode="None" ><GridView.ItemsPanel><ItemsPanelTemplate><VariableSizedWrapGrid Orientation="Horizontal" /></ItemsPanelTemplate></GridView.ItemsPanel></GridView><!--Display command information--><Border Grid.ColumnSpan="2" Grid.Row="2" Background="{StaticResource PS_Headerbrush}" ><Grid><StackPanel HorizontalAlignment="Center"  Orientation="Horizontal"><AppBarButton x:Name="buBack" BorderThickness="5" BorderBrush="WhiteSmoke" Width="100" Background="Transparent" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageProduct}" Icon="Back" Label="Back"  Foreground="White" Style="{StaticResource OverrideAppBarButtonStyle}"/><AppBarButton x:Name="buHome" BorderThickness="5" BorderBrush="WhiteSmoke" Width="100" Background="Transparent" Click="buHome_Click" Icon="Home" Label="Home"  Foreground="White" Style="{StaticResource OverrideAppBarButtonStyle}"></AppBarButton><AppBarButton x:Name="buF" BorderThickness="5" BorderBrush="WhiteSmoke" Width="100" Background="Transparent" Click="buHome_Click" Icon="Mail" Label="Send"  Foreground="White" Style="{StaticResource OverrideAppBarButtonStyle}"></AppBarButton><AppBarButton x:Name="glob" BorderThickness="5" BorderBrush="WhiteSmoke" Width="100" Background="Transparent" Click="buHome_Click" Icon="Map" Label="Map"  Foreground="White" Style="{StaticResource OverrideAppBarButtonStyle}"></AppBarButton><AppBarButton x:Name="msg" BorderThickness="5" BorderBrush="WhiteSmoke" Width="100" Background="Transparent" Click="buHome_Click" Icon="Message" Label="Contact"  Foreground="White" Style="{StaticResource OverrideAppBarButtonStyle}"></AppBarButton></StackPanel></Grid></Border></Grid>

As you can see my page is split in 3 row : 1 header and footer and the midle area.

The header and footer heigh has a fixed value of 80px. SO If I am in a resolution of 1920 by 1080, the middle row of the grid is about 920 px.

So what I am trying to do will layout is that from the picture library which is bind to the ItemsSource, I need to get each picture exactly fit the center grid size. For that I try to get my items to be organized horizontally and then bee able to scroll them horizontally.

The way it is done actually only scrool vertically becasue of the wrappanel. I have try to change the ItemPanel template to use stack panel and horizontal orientation but then I am not able to scrool anymore.

I have try to add this :

<ListView.ItemsPanel><ItemsPanelTemplate><StackPanel Orientation="Horizontal"></StackPanel></ItemsPanelTemplate></ListView.ItemsPanel>
but by doing so, I am not able to sroll anymore

Any idea how can I achieve this ?



Opening new Wpf window from Wpf userControl Hosted in Winform

$
0
0

I have an existing winforms application which we are migrating towards wpf. I have a Winform that loads a Wpf user control, showing a list of items. In that list, there is an edit button that I need to allow the detail of the list item to edited  I have created a Wpf window built to handle the edit.

What I need to do is to open the edit window from the click of the datagrid template button. I have the code working to load the list, and to enter the onclick event of the button.  My problem is that I can't get the edit window to load.  I have seen a few issues where this was addressed, but it was address 5+ years ago and it does not appear applicable to the latest .Net versions.

Can someone point me to the best solution for this.


Joel WZ

How to add stackpanel into grid programmatically

$
0
0

Hello,

I am new to XAML and attempted to add panels with a textblock in it on a grid of 2 rows and 5 items. If my code worked properly, I should expect to see Row 0 Column 0, ... , Row 0... Column 4, ..... Row 1 Column 0, ..., Row 1 Column 4 evenly distributed on my grid. But I do not get that with this code:

My XAML

<Page x:Class="TestUniversal2.MainPage"
			xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
			xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
			xmlns:local="using:TestUniversal2"
			xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
			xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
			mc:Ignorable="d"><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
				x:Name='Test'><Grid.RowDefinitions><RowDefinition Height='*' /><RowDefinition Height='*' /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /></Grid.ColumnDefinitions></Grid></Page>

My Code behind:

namespace TestUniversal2
{
	/// <summary>
	/// An empty page that can be used on its own or navigated to within a Frame.
	/// </summary>
	public sealed partial class MainPage : Page
	{
		public MainPage()
		{
			this.InitializeComponent();
			initiateGrid();
		}

		private void initiateGrid()
		{
			StackPanel sp = null;
			TextBlock tb = null;
			for (int i = 0; i < 2; i++)
			{
				for (int j = 0; j < 5; j++)
				{
					sp = new StackPanel();
					sp.VerticalAlignment = VerticalAlignment.Stretch;
					sp.HorizontalAlignment = HorizontalAlignment.Stretch;
					tb = new TextBlock();
					tb.Text = string.Format("Row {0} Column {1}", i, j);
					tb.FontSize = 50;
					sp.Children.Add(tb);
					Test.Children.Add(sp);
					Grid.SetColumn(Test, j);
					Grid.SetRow(Test, i);
				}
			}
		}
	}
}

What have I done incorrectly?

Please advise.

Thanks!

WPF on Windows for ARM

$
0
0
On Windows for ARM, users and developers are restricted to Windows Forms. Why?

How get/set TreeViewItem height?

$
0
0

I need TreeViewItem height for extend drag&drop.

But TreeViewItem height is NaN. How to set it with xaml?

<TreeView Name="treeView" Grid.Column="0" AllowDrop="True"><TreeView.Resources><Style TargetType="{x:Type TreeViewItem}"><Setter Property="Height" Value="30"/><EventSetter Event="TreeViewItem.DragOver" Handler="treeView_DragOver"/><EventSetter Event="TreeViewItem.Drop" Handler="treeView_Drop"/><EventSetter Event="TreeViewItem.MouseMove" Handler="treeView_MouseMove"/><Setter Property="HeaderTemplate"><Setter.Value><DataTemplate><StackPanel Orientation="Horizontal"><Image Name="img" Width="16" Height="16" Stretch="Fill"
                                                   Source="{Binding RelativeSource=
                                                {RelativeSource Mode=FindAncestor,
                                                AncestorType={x:Type TreeViewItem}},Path=Tag, Converter={StaticResource TagImageConwerter}}"/><TextBlock Text="{Binding}" /></StackPanel></DataTemplate></Setter.Value></Setter></Style></TreeView.Resources></TreeView>

Especially

<Setter Property="Height" Value="30"/>
not set item height to 30 but whole tree height to 30. How set item height to 16 or 18?

bindingsource ui and entity framework 6

$
0
0
Hello.
I started to study the WPF,
1) in the data part, I saw several examples and use objects to store other data to list observablelist to enumerable etc ....
It 'a difference by architectural reasons or just from the date of application and change of entity framework? I use Entity Framework 6.
what are the collections that it is better to use, in short if the speech is complex.
2) In the ui part I use the DevExpress objects but what I do not understand is that until now with win forms I used the BindingSource and relationships (the DataRelation) I do not see more in no instance even if on a book by entity framework She teaches how to use it.
Again , this choice is in the architectural or not?
Because with data relations was simple create multi detail grid , but in entity framework there are the associations....can work as the relations in entity framwork?
bindingsource or not?

thank you.

Create custum control styles for modern ui

$
0
0

how i can create custum control styles for modern ui firstfloor software ??

to costimaze link color and grouplink color ??

this is my personnel code

<UserControl x:Class="Projet.Recources.Manipulation.m_CSup"
             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:mui="http://firstfloorsoftware.com/ModernUI"
             xmlns:Control="http://metro.mahapps.com/winfx/xaml/controls"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300"><Grid Style="{StaticResource ContentRoot}"><mui:ModernTab Layout="List"><mui:ModernTab.Links><mui:Link DisplayName="Ajouter" Source="Recources/Manipulation/m_CS/Ajouter.xaml"/><mui:Link DisplayName="Supprimer" Source="Recources/Manipulation/m_CS/Supprimer.xaml"/><mui:Link DisplayName="Moddifier" Source="Recources/Manipulation/m_CS/Modifier.xaml"/></mui:ModernTab.Links></mui:ModernTab></Grid></UserControl>

I want to get a transparent background for the modernTab links 

Publish WPF application with .mdf database as click Once .exe file (Client PC will not need SQL server installed)

$
0
0

Hello,

I am developing a WPF application on Visual Studio 2013. I used SQL server management Studio and SQL Server 2012 to use .mdf database in my WPF application.

Now I want to publish my application as a clickOnce installation that will produce .exe file and friends of mine can use it and test it on there PC.

But here is a problem My application always want a SQL sever should be installed on testing PC but I won't want that.

I have SQL sever .mdf Database in my developing PC. But I want my WPF application should work in all PC on testing my application and the .mdf database should be embedded on that.

I don't want to use .sdf file.

Thanks in advance:)


DelegateCommand

$
0
0
        private DelegateCommand<object> _GuncelleCommand;
        public ICommand GuncelleCommand
        {
            get
            {
                if (_GuncelleCommand == null)
                {
                    _GuncelleCommand = new DelegateCommand<object>(new Action<object>(this.BelgeGuncelle), new Func<bool>(() => this.IsGuncellemeTrue));
                }
                return _GuncelleCommand;
            }
        }
        public bool IsGuncellemeTrue
        {
            get { return true; }
        }

and

       public void BelgeGuncelle(object parameter)
        {
            MessageBox.Show("Test");

        }

How Can I use with the following Treeviewitem of thepart DelegateCommand;

<TreeView.ItemContainerStyle><Style TargetType="{x:Type TreeViewItem}"><EventSetter Event="UIElement.PreviewMouseLeftButtonDown" Handler="SelectedTreeView"/><Style.Triggers><Trigger Property="IsSelected" Value="True"><Setter Property="IsExpanded" Value="False"/><Setter Property="FontWeight" Value="Bold"/><Setter Property="FontStyle" Value="Italic"/><Setter Property="Foreground" Value="Red"/></Trigger></Style.Triggers></Style></TreeView.ItemContainerStyle>
Thanks;



Update table from entity using EF, HierarchicalDataTemplate and TreeView

$
0
0

I have a hierarchically recursive (self-referencing) table that I am showing using Entity Framework, a HierarchicalDataTemplate and a TreeView. It works but now I want to support modifying the data. I am able to do a rename of a node and the modification is applied to the table but it does not show in the TreeView until I exit the application and execute again. I am sure I can get it to work using a hack but I want to do it using something that is supported.

I have a table with the fields Id, OfId and Category. The "OfId" is the parent id, as in a category of another category. So that creates the hierarchical recursion.

My Window_Loaded does a LINQ and the result of the LINQ is a "IQueryable<Category>". That is assigned to a variable called "result" and then Window_Loaded does:

treeView1.ItemsSource = result.ToList();

My XAML for the TreeView is:

<TreeView Name="treeView1" Grid.Column="0" Width="200" HorizontalAlignment="Left"><TreeView.ItemTemplate><HierarchicalDataTemplate ItemsSource="{Binding Categories1}" ><TextBlock Text="{Binding Category1, Mode=TwoWay}" /></HierarchicalDataTemplate></TreeView.ItemTemplate></TreeView>

I have a context menu and when the menu item for a rename is selected the following will rename the text (this is just for testing purposes):

if (treeView1.SelectedValue == null)
    return;
Category c = treeView1.SelectedValue as Category;
if (c == null)
    return;
c.Category1 += 'x';
WhateverContext.SaveChanges();
MessageBox.Show("Rename " + c.Category1);

As I said, the text gets the "x" appended but the change does not appear in the TreeView until I restart he application.

The following is the complete "Category" class:

public partial class Category
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Category()
    {
        this.Categories1 = new HashSet<Category>();
        this.Sites = new HashSet<Site>();
    }

    public int Id { get; set; }
    public int OfId { get; set; }
    public string Category1 { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Category> Categories1 { get; set; }
    public virtual Category Category2 { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Site> Sites { get; set; }
}



Sam Hobbs
SimpleSamples.Info





Get the Value of WPF Listview rows and compare them with database field using Linq query

$
0
0

i want to compare ECH_INTITULE in my database with the values of the listview rows but my problem is that i can't access the Listview items in my Linq query

here is my Xaml code for my Listview :

<ListView x:Name="listView" SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding}" DataContext="query" HorizontalAlignment="Left" Height="430" Margin="24,47,0,0" VerticalAlignment="Top" Width="940" ><ListView.View><GridView x:Name="gridView"><GridViewColumn Header="Fournisseur" DisplayMemberBinding="{Binding fournisseur}" Width="280"/><GridViewColumn Header ="Adresse Mail" DisplayMemberBinding="{Binding email}" Width="270"/><GridViewColumn Header ="Date" DisplayMemberBinding="{Binding date}" Width="150"/><GridViewColumn Header="Fichier CSV" DisplayMemberBinding="{Binding xxx}" Width="105"/><GridViewColumn Header="Fichier PDF" DisplayMemberBinding="{Binding xxx}" Width="105"/></GridView></ListView.View></ListView>

and here is my c# code :

//Generate CSV Files for each item in the Listview
            CsvFileDescription outpCsvFileDescription = new CsvFileDescription
            {
                SeparatorChar = ',',
                FirstLineHasColumnNames = true
            };

            for (int i = 0; i < listView.Items.Count; i++)
            {
                var infoEcheances = from f in db.F_ECHEANCES
                                    //where f.ECH_Intitule == ???
                                    select new { f.ECH_Intitule, f.ECH_DateEch, f.CG_Num, f.ECH_Piece, f.ECH_RefPiece, f.ECH_Montant, f.ECH_Libelle };


                CsvContext cc = new CsvContext();
                string myPath = @C:\Users\DefaultAccount\Desktop\Projet Top Of Travel\FichiersCSV\";
                string filename = string.Format("Facture{0}.csv", i);
                string finalPath = System.IO.Path.Combine(myPath, filename);
                cc.Write(infoEcheances, finalPath, outpCsvFileDescription);
            }



How to make extended TreeView Drag&Drop?

$
0
0

I based on article www.codeproject.com Drag-and-Drop-Feature-in-WPF-TreeView-Control

but I want add extensions:

first, two modes of dropping: If user drops at center node - it normally move dragging node to this node as subnode, but if not center - insert dragging node between nodes. I need TreeViewItem.Height to distinguish: if height = 16, then center is 4..12 else between. I can't use TreeViewItem.ActualHeight because for expanded nodes it give me height node and childs of this node.

TreeViewItem.Height give me NaN because is not set. I tried set this height in xaml, but only set height of StackPanel of TreeViewItem. Then TreeViewItem.Height still give me NaN, how get height od StackPanel?

Second question: If I move dragged node, how to enable automatic scrolling TreeView when mouse is above or below window?

I attach my project in VS2013: Project on drive.google.com

WriteableBitmap memleak problem

$
0
0

Hello.

I have a writeableBitmap and it has a memleak - memleak

I have found a workaround which is to call bitmap.Freeze() if we don't need this bitmap anymore and it works fine except one small problem. It's inside wpf user control and i don't know exactly when it will be destroyed. Probably I can solve it by using some user control event but in any case i'd like a general solution. I tried to do Freeze() in the finalizer but it's not possible since it can be done only from bitmap creation thread. So, what would be your suggestion?

WPF MVVM simple form with a drop down

$
0
0

I am looking for an example of a wpf xaml form using MVVM. 

I have one class of employees name, age.  and another class with a list of states.

I need one form with a combo box drop down for states and the two other fields(name, age) 

Originally I did this using the xaml code behinds but I want to use the MVVM pattern. 

Thanks for the help


Performing calculations after passing through IDataErrorInfo using binding

$
0
0

I am fairly new to C# and I'm teaching myself WPF in the process. I can't seem to find a solution for my problem after hours of searching. I have a demo app I'm writing that accepts input values on 3 fields. If data is input in one field, the other fields should be calculated and updated. The user should be able to input numeric values in any of the 3 fields and the other fields will be calculated.

Furthermore, I'm using IDataErrorInfo for validation and using binding in MVVM, WPF application. The code somewhat works, but has an issue with input since the fields can also be calculated. IE, when I input data in the view, its value gets changed due to the calculations. Also, if I key something with a decimal in it, it gets even worse, often not even accepting the decimal, or accepting a 0 after a decimal, such as 1.056, which stops at 1.0. It appears the problem is with the indexer, but I don't know C#, MVVM, and binding well enough to know how to fix it, and I'm only just now learning how IDataErrorInfo works specifically, the indexer.

Below is the code, which will successfully execute, but exhibit the problems listed above. However, the view is not entirely completed as I have yet to bind a textbox for the IDataErrorInfo error messages. Any advice would be appreciated.

View - MainWindow.xaml

<Window x:Class="NumberConverterforWin.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:NumberConverterforWin"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="Number Converter 1.0" Height="150" Width="350"><Grid Margin="0,0,0,0"><Grid.Background><SolidColorBrush Color="{DynamicResource {x:Static SystemColors.MenuHighlightColorKey}}"/></Grid.Background><Grid.RowDefinitions><RowDefinition Height="33*"/><RowDefinition Height="33*"/><RowDefinition Height="33*"/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="33*"/><ColumnDefinition Width="33*"/><ColumnDefinition Width="33*"/></Grid.ColumnDefinitions><TextBlock
            x:Name="multiplier1text"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Margin="0,0,0,0"
            TextWrapping="Wrap"
            Text="Multiplier 1"
            FontWeight="Bold"
            /><TextBlock
            x:Name="differencetext"
            Margin="10,0"
            TextWrapping="Wrap"
            Text="Difference"
            Grid.Row="1"
            FontWeight="Bold"
            HorizontalAlignment="Center"
            TextAlignment="Center"
            VerticalAlignment="Center"
            /><TextBlock
            x:Name="multiplier2text"
            Margin="0"
            TextWrapping="Wrap"
            Text="Multiplier 2"
            VerticalAlignment="Center"
            Grid.Row="2"
            FontWeight="Bold"
            HorizontalAlignment="Center"
            TextAlignment="Center"
            /><TextBox
            x:Name="multiplier1"
            Grid.Column="1"
            HorizontalAlignment="Center"
            Margin="10,9"
            Text="{Binding Path=Multiplier1, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
            VerticalAlignment="Center"
            Width="90"
            VerticalContentAlignment="Center"
            MaxLines="1"
            /><TextBox
            x:Name="difference"
            Grid.Column="1"
            HorizontalAlignment="Center"
            Margin="10,9"
            Grid.Row="1"
            Text="{Binding Path=Difference, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
            VerticalAlignment="Center"
            Width="90"
            VerticalContentAlignment="Center"
            MaxLines="1"
            /><TextBox
            x:Name="multiplier2"
            Grid.Column="1"
            HorizontalAlignment="Center"
            Margin="10,9"
            Grid.Row="2"
            Text="{Binding Path=Multiplier2, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
            VerticalAlignment="Center"
            Width="90"
            VerticalContentAlignment="Center"
            MaxLines="1"
            /></Grid></Window>


MainWindow.xaml.cs

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.Navigation;
using System.Windows.Shapes;

namespace NumberConverterforWin
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Model initial = new Model(0, 100, 0);
            base.DataContext = new Converter(initial);
        }
    }
}

ViewModel - converter.cs

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

namespace NumberConverterforWin
{
    public class Converter : INotifyPropertyChanged, IDataErrorInfo
    {
        readonly Model _model;
        string _multiplier1Text;
        string _differenceText;
        string _multiplier2Text;
        string _propertyText;

        public Converter(Model model)
        {
            _model = model;
            _multiplier1Text = model.Multiplier1.ToString();
            _differenceText = model.Difference.ToString();
            _multiplier2Text = model.Multiplier2.ToString();
        }

        public string Multiplier1
        {
            get
            {
                return _multiplier1Text;
            }

            set
            {
                if (value == _multiplier1Text)
                    return;

                _multiplier1Text = value;

                this.OnPropertyChanged("Multiplier1");

            }
        }

        public string Difference
        {
            get
            {
                return _differenceText;
            }

            set
            {
                if (value == _differenceText)
                    return;
                _differenceText = value;

                this.OnPropertyChanged("Difference");
            }
        }

        public string Multiplier2
        {
            get
            {
                return _multiplier2Text;
            }

            set
            {
                if (value == _multiplier2Text)
                    return;
                _multiplier2Text = value;

                this.OnPropertyChanged("Multiplier2");
            }
        }


        #region IDataErrorInfo Members

        public string Error
        {
            get { return _model.Error; }
        }

        public string this[string propertyName]
        {
            get
            {
                double propertyvalue;

                string msg;
                double _factor;

                switch (propertyName)
               {
                    case "Multiplier1":

                        _propertyText = _multiplier1Text;
                        msg = this.Validate(propertyName, out propertyvalue);
                        if (!String.IsNullOrEmpty(msg))
                            return msg;

                        _model.Multiplier1 = propertyvalue;
                        _factor = propertyvalue * 70;
                        _model.Difference = Math.Round(100 - _factor, 4);
                        _model.Multiplier2 = Math.Round(_factor / 40, 4);


                        break;

                    case "Difference":

                        _propertyText = _differenceText;
                        msg = this.Validate(propertyName, out propertyvalue);
                        if (!String.IsNullOrEmpty(msg))
                            return msg;

                        _model.Difference = propertyvalue;
                        _factor = 100 - propertyvalue;
                        _model.Multiplier1 = Math.Round(_factor / 70, 4);
                        _model.Multiplier2 = Math.Round(_factor / 40, 4);
                        break;

                    case "Multiplier2":

                        _propertyText = _multiplier2Text;
                        msg = this.Validate(propertyName, out propertyvalue);
                        if (!String.IsNullOrEmpty(msg))
                            return msg;

                        _model.Multiplier2 = propertyvalue;
                        _factor = propertyvalue * 40;
                        _model.Multiplier1 = Math.Round(_factor / 70, 4);
                        _model.Difference = Math.Round(100 - _factor, 4);
                        break;
                }

                Difference = _model.Difference.ToString();
                Multiplier2 = _model.Multiplier2.ToString();
                Multiplier1 = _model.Multiplier1.ToString();

                return _model[propertyName];
            }
        }

        string Validate(string propertyname, out double propertyvalue)
        {
            propertyvalue = -1;
            string msg = null;

            if (String.IsNullOrEmpty(_propertyText))
                msg = propertyname + " is missing.";

            if (!Double.TryParse(_propertyText, out propertyvalue))
                msg = propertyname + " is not a numeric value.";
            return msg;
        }

        #endregion // IDataErrorInfo Members


        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

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

        #endregion // INotifyPropertyChanged Members
    }
}



Model - model.cs

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

namespace NumberConverterforWin
{
    public class Model : IDataErrorInfo
    {
        public Model(double multiplier1, double difference, double multiplier2)
        {
            this.Multiplier1 = multiplier1;
            this.Difference = difference;
            this.Multiplier2 = multiplier2;
        }

        public double Multiplier1 { get; set; }
        public double Difference { get; set; }
        public double Multiplier2 { get; set; }

        #region IDataErrorInfo Members

        public string Error
        {
            get { return null; }
        }
        public string this[string propertyName]
        {
            get
            {
                if (propertyName == "Multiplier1")
                {
                    if (this.Multiplier1 < 0)
                        return "Multiplier1 cannot be less than 0.";

                    if (1.4286 < this.Multiplier1)
                        return "Multiplier 1 cannot be greater than 1.4286.";
                }

                if (propertyName == "Difference")
                {
                    if (this.Difference < 0)
                        return "Difference cannot be less than 0.";

                    if (100 < this.Multiplier1)
                        return "Difference cannot be greater than 100.";
                }

                if (propertyName == "Multiplier2")
                {
                    if (this.Multiplier2 < 0)
                        return "Multiplier 2 cannot be less than 0.";

                    if (2.5 < this.Multiplier2)
                        return "Multiplier 2 cannot be greater than 2.5.";
                }

                return null;
            }
        }

        #endregion // IDataErrorInfo Members
    }
}




How to dynamically create grid structure

$
0
0

This question is a continuation of the previous question asked on this board:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/62bdba6a-8ec3-4c8d-866e-1ea90cba7e1e/how-to-add-stackpanel-into-grid-programmatically?forum=wpf

The response for the question above solved my issue but I was suggested to create a new thread if I have follow up question or want to expand the scope of the question. The question above was based on the static grid created on xaml

<Grid.RowDefinitions><RowDefinition Height='*' /><RowDefinition Height='*' /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /></Grid.ColumnDefinitions>

However, I would like to create the grid at run time as I do not know the exact structure of the grid at design time.

So, I expanded my existing initiategrid method and removed the xaml above

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
				x:Name='Test'><!--<Grid.RowDefinitions><RowDefinition Height='*' /><RowDefinition Height='*' /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /><ColumnDefinition Width='*' /></Grid.ColumnDefinitions>--></Grid>
		public MainPage()
		{
			this.InitializeComponent();
			initiateGrid();
		}

		private void initiateGrid()
		{
			for (int i = 0; i < 2; i++)
			{
				RowDefinition r = new RowDefinition();
				Test.RowDefinitions.Add(r);
				for (int j = 0; j < 5; j++)
				{
					ColumnDefinition c = new ColumnDefinition();
					c.Width = new GridLength(1, GridUnitType.Star);
					Test.ColumnDefinitions.Add(c);

					StackPanel sp= new StackPanel();
					TextBlock tb = new TextBlock();
					sp.VerticalAlignment = VerticalAlignment.Stretch;
					sp.HorizontalAlignment = HorizontalAlignment.Stretch;

					tb.Text = string.Format("({0}, {1})", i, j);
					tb.FontSize = 20;
					sp.Children.Add(tb);
					Test.Children.Add(sp);
					Grid.SetColumn(sp, j);
					Grid.SetRow(sp, i);
				}
			}
		}

I do not get compiling error nor do I get run time error. But the grid structure does not seem to be created properly because the textBlock positions are way different than the positions of the static grid. Can we not recreate the grid structure by code?

Please advise. Thanks!

Create dynamic grid structure using independency injection

$
0
0

This question is an extension of my previous question:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/1d66106b-e24e-4014-a9ba-aae1d5d33ac1/how-to-dynamically-create-grid-structure?forum=wpf

The response for the question above was clearly understood. But I ran across an interesting material from Rachel that used dependency injection and I wonder how it could be applicable to my case.

https://rachel53461.wordpress.com/2011/09/17/wpf-grids-rowcolumn-count-properties/

I used Rachel's GridHelpers class and applied to my xaml static structure. It worked!

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
				x:Name='Test'
				local:GridHelpers.RowCount='2'
				local:GridHelpers.ColumnCount='5'
				local:GridHelpers.StarColumns='0,1,2,3,4'
				local:GridHelpers.StarRows='0,1'>

However, when I tried to bind it to a property to initialize it at run time, no error but no result

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
				x:Name='Test'
				local:GridHelpers.RowCount='{Binding rowCount, Mode=TwoWay}'
				local:GridHelpers.ColumnCount='{Binding colCount, Mode=TwoWay}'
				local:GridHelpers.StarColumns='{Binding starCol}'
				local:GridHelpers.StarRows='{Binding starRow}'>

My Code:

public sealed partial class MainPage : Page
	{
		private int _rowCount;
		private int _colCount;
		private string _starCol;
		private string _starRow;

		public string starRow
		{
			get { return _starRow; }
			set { _starRow = value; }
		}


		public string starCol
		{
			get { return _starCol; }
			set { _starCol = value; }
		}

		public int colCount
		{
			get { return _colCount; }
			set { _colCount = value;}
		}

		public int rowCount
		{
			get { return _rowCount; }
			set { _rowCount = value; }
		}

		public MainPage()
		{
			this.InitializeComponent();
			initiateGrid();
		}

		private void initiateGrid()
		{
			rowCount = 2;
			colCount = 5;
			starCol = "0,1,2,3,4";
			starRow = "0,1";
			for (int i = 0; i < 2; i++)
			{
				for (int j = 0; j < 5; j++)
				{

					StackPanel sp = new StackPanel();
					TextBlock tb = new TextBlock();
					sp.VerticalAlignment = VerticalAlignment.Stretch;
					sp.HorizontalAlignment = HorizontalAlignment.Stretch;

					tb.Text = string.Format("({0}, {1})", i, j);
					tb.FontSize = 20;
					sp.Children.Add(tb);
					Test.Children.Add(sp);
					Grid.SetColumn(sp, j);
					Grid.SetRow(sp, i);
				}
			}
		}

What was not done correctly? I know this is not a good way to build UI, but I am just curious why the code does not yield result it supposed to? There must be a piece that I have missed as I am very new to xaml, binding...

Thanks!

Other event is not working inside ScrollViewer with Touch Screen

$
0
0

I want to implement touch scrolling in the list view when we test application without touch screen then its working fine but when we test on touch screen then List view Selection changed is not working but scrolling is working. why?

<ScrollViewer Grid.Column="1" Grid.Row="1"  VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Auto" PanningMode="HorizontalOnly"  ManipulationBoundaryFeedback="ScrollViewerCanvas_ManipulationBoundaryFeedback"></ScrollViewer>


How to find index number of list view on touch down of scrollviewer in WPF

$
0
0

I have control template. look my Code :

<ControlTemplate x:Key="ListBoxTemplate" TargetType="{x:Type telerik:ListView}"><DockPanel><RepeatButton x:Name="btnScrollLeft" DockPanel.Dock="Left" Width="20" Content="M 8 0 L 8 32 L 0 16 Z" Click="btnScrollLeft_Click"/><RepeatButton x:Name="btnScrollRight" DockPanel.Dock="Right" Width="20" Content="M 0 0 L 8 16 L 0 32 Z" Click="btnScrollRight_Click"/><Border BorderThickness="1" BorderBrush="Gray" Background="White"><ScrollViewer x:Name="sv" ScrollChanged="sv_ScrollChanged"

ManipulationBoundaryFeedback="sv_ManipulationBoundaryFeedback" PreviewTouchUp="sv_PreviewTouchUp"

TouchDown="sv_TouchDown" PanningMode="HorizontalOnly"><ItemsPresenter/></ScrollViewer></Border></DockPanel></ControlTemplate>

I want to know how to find touch Hold/pressed  list view Item on the PreviewTouchUp event. Look Code:

private void sv_PreviewTouchUp(object sender, TouchEventArgs e) { if (DateTime.Now - lastTouchDown < TimeSpan.FromMilliseconds(300)) { ScrollViewer sv = sender as ScrollViewer; ListViewItem lvi = (ListViewItem)sv.DataContext; lvi.IsSelected = true;

ItemsPresenter itemsPresenter = GetVisualChild<ItemsPresenter>(sv); Panel itemsPanel = VisualTreeHelper.GetChild(itemsPresenter, 0) as Panel; // Touch and finger off screen } else {

// They kept their finger down a while } }

Preview Touch up event is working fine. But I want to know how to find pressed or hold list view item. Please guide me.

Thanks in advance.

WPF MVVM accepts input from weight scale

$
0
0

I am working on an application that originally was done using the code behind for the xaml pages. I am converting it to use the MVVM pattern.  I have code that will accept the input from a usb scale populate the text box using DispatcherTimer  to poll the scale when I used the code behind format. But where should I put this code to populate the text box from the weight scale in the MVVM format? 

I am starting to get the hang of the MVVM pattern but still have a way to go, I appreciate all the help I have been getting.

Thanks you

Viewing all 18858 articles
Browse latest View live


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