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

WPF DataGrid TwoWay Binding - What's Wrong?

$
0
0

Hi all,

I need help understanding why I can't edit the data grid so that the changes are reflected in the bound data. I have the following class:

public class Player : INotifyPropertyChanged
    {
        public Player()
        {

        }
        public Player(string name)
        {
            _name = name;
        }

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

        private ObservableCollection<int> _gameScoreList = new ObservableCollection<int>();
        public ObservableCollection<int> GameScoreList
        {
            get { return _gameScoreList; }
            set
            {

                if (_gameScoreList != value)
                {
                    _gameScoreList = value;
                    FirePropertyChanged("GameScoreList");
                }

            }
        }

        private string _currentScore = "";
        public string CurrentScore
        {
            get { return this.GameScoreList.Sum().ToString(); }
            set
            {
                _currentScore = value;
                FirePropertyChanged("CurrentScore");
            }
        }

        private string _lastWordScore;
        public string LastWordScore
        {
            get { return this.GameScoreList.Last<int>().ToString(); }
            set
            {
                _lastWordScore = value;
                FirePropertyChanged("LastWordScore");
            }
        }

        private bool _turn = false;
        public bool Turn
        {
            get { return _turn; }
            set { _turn = value; FirePropertyChanged("Turn"); }
        }
        private string _currentWord = "";
        public string CurrentWord
        {
            get { return _currentWord; }
            set
            {
                _currentWord = value;
                FirePropertyChanged("CurrentWord");
            }
        }

        private List<Game> _gameHistory = new List<Game>();
        public List<Game> GameHistory
        {
            get { return _gameHistory; }
            set { _gameHistory = value; }
        }

        private void FirePropertyChanged(string property)
        {

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

I have the following DataGrid:

<DockPanel x:Name="dp1" Grid.Column="1" HorizontalAlignment="Stretch" Grid.RowSpan="2"><WrapPanel x:Name="spP2Name" DockPanel.Dock="Top" Margin="60, 0, 0, 0" Orientation="Horizontal" HorizontalAlignment="Center"></WrapPanel><TextBox x:Name="tbP2Curr" DockPanel.Dock="Top" MinWidth="150" HorizontalAlignment="Center" TextAlignment="Center" VerticalAlignment="Center" Text="{Binding Path=CurrentWord}" Style="{StaticResource TotalHeaderStyle}"></TextBox><DataGrid x:Name="dgP2Scores"  DockPanel.Dock="Top" ItemsSource="{Binding Path=GameScoreList, Mode=TwoWay, NotifyOnTargetUpdated=True, UpdateSourceTrigger=LostFocus}" IsReadOnly="False"><DataGrid.Columns><DataGridTextColumn Binding="{Binding Path=., Mode=TwoWay}"/></DataGrid.Columns></DataGrid></DockPanel>

I've then set the DataContext of my DockPanel to a Player Class like so:

dp1.DataContext = p;

Now I can happily add new items to the datagrid, but if I try and manually overwrite one by editing a DataGrid cell then it doesn't change, nor does it try to change.

I've got to be doing something daft here but I just can't see what?

Thanks all,

Jib


Regarding to AppDomain.CurrentDomain.UnhandledException and logging.

$
0
0

Hi,

I used to work with Logging but can't regonize it how to do it with the right way.

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

private static void HandleException(Exception ex) { if (ex == null) return;

this.logger.WriteMessage("");

// Do I need to put the Thread.Sleep here? MessageBox.Show(OnScreen_v2.Properties.Resources.UnhandledException); Environment.Exit(1); }

Do I need to put the Thread's sleep method there? I need to write error message to local disk.


Is it possible to simplify Grid Definition and when you have many rows and columns?

$
0
0

I have many blocks in my WPF windows which define the following GRID:

<Grid Width="960"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /></Grid.ColumnDefinitions>
...

Is is possible to write something like (pseudocode):

<Window.Resources><GridTemplate Width="960" Name="myTemplate"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /><ColumnDefinition Width="80" /></Grid.ColumnDefinitions></GridTemplate></Window.Resources>
...<Grid Template="myTemplate"><!-- No need to further include RowDefinitions or ColumnDefinitions, just include your stuff here --></Grid>

Or something like (pseudocode):

<Grid Width="960"><Grid.RowDefinitions>
		5*<RowDefinition Height="Auto"/></Grid.RowDefinitions><Grid.ColumnDefinitions>
		12*<ColumnDefinition Width="80" /></Grid.ColumnDefinitions>
        ...</Grid>

Thanks,

Custom Canvas control's dependency property not visible in XAML intellisense

$
0
0

Hello. I have a custom Canvas control where I've defined a dependency property in the code-behind file as follows:

public partial class ImageCelOverlay : Canvas
{
    public static readonly DependencyProperty TranslationXProperty = DependencyProperty.Register("TranslationX", typeof(Double),  typeof(ImageCelOverlay), new PropertyMetadata(0.0));

    public Double TranslationX
        {
            get { return (Double)GetValue(TranslationXProperty); }
            set { SetValue(TranslationXProperty, value); }
        }

In the same controls XAML file I try to access the above dependency property to bind it to something but it will not appear in the intellisesne and, indeed, gives me a red squiggly if I try to use it anyway. I've tried rebuilding and restarting VS 2015 but I can't get it to show up. What am I doing wrong here? Thank you in advance.

-L

Using variables to define Grid.Row in XAML / WPF

$
0
0
While defining a Form using XAML, I am chaining several blocks of fields.
In order to make XAML code more readable and maintenable in the future, I am trying to define a "base" Row for each block, so relative Rows can be used to define each item of the block instead of absolute ones.

Note the differences for:

    < ... Grid.Row="" ...>



in both cases.

Here is an excerpt of my current code:

<!-- Subblock 2 --><!-- Address --><Label Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" HorizontalContentAlignment="Right" Content="Address:"/><TextBox Grid.Row="5" Grid.Column="2" Grid.ColumnSpan="4" HorizontalContentAlignment="Center" Text="Address"/>   <TextBox Grid.Row="6" Grid.Column="2" Grid.ColumnSpan="4" HorizontalContentAlignment="Center" Text="Address (cont.)"/>   <TextBox Grid.Row="7" Grid.Column="2" Grid.ColumnSpan="2" HorizontalContentAlignment="Center" Text="Town"/>   <TextBox Grid.Row="7" Grid.Column="4" Grid.ColumnSpan="2" HorizontalContentAlignment="Center" Text="ZIP"/>   <TextBox Grid.Row="8" Grid.Column="2" Grid.ColumnSpan="2" HorizontalContentAlignment="Center" Text="State"/>   <TextBox Grid.Row="8" Grid.Column="4" Grid.ColumnSpan="2" HorizontalContentAlignment="Center" Text="Country"/>


And this is what I would like to have:

<Window.Resources>           <!-- Defines starting rows for each block -->           <System:Int32 x:Key="rowBlock1">0</System:Int32>           <System:Int32 x:Key="rowBlock2">5</System:Int32>   </Window.Resources>    [...]   <!-- Subblock 2 -->   <!-- Address -->   <Label Grid.Row="{StaticResource rowBlock2} + 0" Grid.Column="0" Grid.ColumnSpan="2" HorizontalContentAlignment="Right" Content="Address:"/>   <TextBox Grid.Row="{StaticResource rowBlock2} + 0" Grid.Column="2" Grid.ColumnSpan="4" HorizontalContentAlignment="Center" Text="Address"/>   <TextBox Grid.Row="{StaticResource rowBlock2} + 1" Grid.Column="2" Grid.ColumnSpan="4" HorizontalContentAlignment="Center" Text="Address (cont.)"/>   <TextBox Grid.Row="{StaticResource rowBlock2} + 2" Grid.Column="2" Grid.ColumnSpan="2" HorizontalContentAlignment="Center" Text="Town"/>   <TextBox Grid.Row="{StaticResource rowBlock2} + 2" Grid.Column="4" Grid.ColumnSpan="2" HorizontalContentAlignment="Center" Text="ZIP"/>   <TextBox Grid.Row="{StaticResource rowBlock2} + 3" Grid.Column="2" Grid.ColumnSpan="2" HorizontalContentAlignment="Center" Text="State"/>   <TextBox Grid.Row="{StaticResource rowBlock2} + 3" Grid.Column="4" Grid.ColumnSpan="2" HorizontalContentAlignment="Center" Text="Country"/>


Is is possible to achive that with XAML? Any other tip/suggestion on how to avoid absolute Grid.Row values is also welcomed.

How to dynamically add tab to ribbon using code

$
0
0

I am working on a project which need load the Ribbon tab dynamically based on the configuration when the program starts up. I can only found a way to add the tab to the Ribbon as 

Ribbon.Items.Add(tab)

But an exception throw out:

Items collection must be empty before using ItemsSource.

Here is the code in xaml:

    <Grid Name="RootGrid">
        <Grid.RowDefinitions>
            <RowDefinition Height="140"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>

<ribbon:Ribbon Name="m_RibbonRoot"/>

        <Grid Name="m_WindowContent" Grid.Row="1">
            <!-- Here is the content of the window-->
        </Grid>
    </Grid>

Here is the code behind:

        private void InitializeRibbonUI()
        {
            var tabs = RibbonUIManager.Instance.GetTabList();     //Get the list of the tabs from the configuration
            foreach (var tab in tabs)
            {
                m_RibbonRoot.Items.Add(tab);                               //Exception thrown: Items collection must be empty before using ItemsSource.
            }
         }

I am using Ribbon for WPF (System.Windows.Controls.Ribbon) in .net 4.5.1

Thank you very much

Best regards,

Xin 


Deploying WPF application with Local Database

$
0
0

 I have made an Wpf application that has local database i.e service based database but whenever i tried to deploy it to another pc it says it stopped working Do i need something to install on other PC's in order to run this? because the database is not picked by other pcs even though i have attached the .mdf file. please help me out Thanks in advance

Regards,

 

WPF DataGrid - Setter not triggered on LostFocus

$
0
0

This issue is about a DataGrid in a xaml UserControl. It has the usual binding of the ItemsSource to an ObservableCollection. The class in the ObservableCollection is a kind of ViewModel with Setter properties (saving changes to the DB).

When the binding is defined as PropertyChanged, it works as expected. The problem occurs when LostFocus is set and I can see a weird behaviour: only a tab from the end of a row to the next makes the trigger fire. After pressing enter or clicking on another row I see the WPF DataGrid updated but the Property Setter doesn't get called at all!

Is it an open bug?



undefined CLR namespace

$
0
0

I try to build this,but with no succes. Thank you!

Resizing Bitmap to increase image quality

$
0
0

I have an application that gets and saves a picture of an open window. Unfortunately, when the dimensions of the image and window match, the image quality is unacceptably low. I've increased the size the of the RenderTargetBitmap, which has increased the image quality, however, now the dimensions of the resulting image are too large for my purposes.

My question is this: Is there any way to resize the resulting RenderTargetBitmap to the original dimensions of the window? And is it possible to do this without a corresponding loss in image quality? Here's the code I have now.

public static RenderTargetBitmap GetReportImage(Grid view) { // Increased dimensions to increase image quality Size size = new Size(view.ActualWidth * 2, view.ActualHeight * 2 ); // The dimensions that I want to convert back to. _size = new Size(view.ActualWidth, view.ActualHeight); if (size.IsEmpty) return null; RenderTargetBitmap result = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96 , 96 , PixelFormats.Pbgra32); DrawingVisual drawingVisual = new DrawingVisual(); using (DrawingContext context = drawingVisual.RenderOpen()) { context.DrawRectangle(new VisualBrush(view), null, new Rect(new Point(), size)); context.Close(); } result.Render(drawingVisual); // Can I resize result to _size.Width and _size.Height?


return result; }

Thanks in advance for any help.

Note: I tried calling this drawingVisual.Transform = new ScaleTransform(_size.Width, _size.Height); before rendering the result, but the jpg was just one solid color. 


How to implement google cloud print windows phone 8.1 winRT in wpf?

$
0
0
I have to print a file using google cloud print in windows 8.1 WinRT application.Help me to implement...

WPF MediaElement mess up when play loop.

$
0
0

WPF MediaElement

As the sample, When my application is full screen, and then active another app, when I back to the sample application, the video mess up!

Window Height & Width according to scree resolution

$
0
0

How to manage window height and width , according to change screen resolution

<window>

     <Grid>

            <StackPanel Oriention="Vertical">

                  <TextBox........./>

                   <TextBox........./>

                   <Button........./>

            </StackPanel>

     </Grid>

</window>

How to Height & Width Manage according to change screen resolution...

Screen Resolutions :

1366 X 768

1360 X 768

1280 X 768

1280 X 720

1024 X 768

800 X  600

How to manage window height and width


A.Acharya Feedback to us Develop and promote your apps in Windows Store Please remember to mark the replies as answers if they help and unmark them if they provide no help.

Dropdown issues in WPF Webbrowser control when viewing IE11 compatible website

$
0
0

Hi,

I have created a WPF application, in which we are using webbrowser control to view asp.net website which is created according to latest IE-11Edge Mode.

In this website we have multiple dropdown controls. when we click on the dropdown in webbrowser control, its popup container width is less than dropdown width. Even if, we press the [esc] key to close the popup container of dropdown, it is also not working.


Approaches I have tried to resolved this issue;

1. I have added meta tag in asp.net page <meta http-equiv="x-ua-compatible" content="IE=edge" >

2. I have register my WPF application .exe file name in registery on [HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION] path with value 11001.


But unfortunately none of them are working.

Please suggest any solution in this case.


Thanks & Regards,

Ajay Singh

Dropdown issues in WPF Webbrowser control when viewing IE11 compatible website

$
0
0

Hi,

I have created a WPF application, in which we are using webbrowser control to view asp.net website which is created according to latest IE-11Edge Mode.

In this website we have multiple dropdown controls. when we click on the dropdown in webbrowser control, its popup container width is less than dropdown width. Even if, we press the [esc] key to close the popup container of dropdown, it is also not working.

Approaches I have tried to resolved this issue;

1. I have added meta tag in asp.net page

2. I have register my WPF application .exe file name in registery on [HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION] path with value 11001.

But unfortunately none of them are working.

Please suggest any solution for this case.

Thanks & Regards,

Ajay Singh


UserControl Button IsCancel not honoring e.Handled still calls DialogCancelCommand

$
0
0

Has anyone come across the .NET Framework *BUG* in the WPF button where it does not honor the "e.Handled = true" value in the OnClick method(s) and instead proceeds to processing Command bindings? 

Specifically I'm slowly uplifting code from the WinForms style of programming over to MVVM.  I have a user control with a Cancel button which has a ClickEventHandler wired up and has the IsCancel = true set.  In the code behind the UserControl is wired into the host container Window's Closing event in order to prevent the user from closing the form via the X which the control is dirty.  This is done by setting the Window's Closing e.Handle = true. 

What I'm seeing is the Window's Closing Event is being called twice as the when the Button is wired up without a Command but is marked with IsCancel = True, the framework code is still calling theMS.Internal.Commands.CommandHelpers.ExecuteCommand(Window.DialogCancelCommand, null, this);  In other words the Button.OnClick() and BaseButton.OnClick() simply ignore the RoutedEventArgs.Handled property and keep chugging on calling the MS.InternalCommands.CommandHelpers.ExecuteCommandSource(this) andExecuteCommand() with no regards

So far the only thing I can come up with is to convert the EventHandlers over to ICommands.  Anyone else have ideas on getting around this issue?

Simple line graph with no markers using WPF Toolkit Chart for WPF

$
0
0
I'm trying to create a simple line graph with no markers using the Chart control in the WPF toolkit.  I have a lot of data points, and the line looks very clunky with tons and tons of markers on it.  All I really need is a way for the user to visualize the line, not to examine every individual data point.

So far I haven't had much luck with this.  Here's my line:

<charting:Chartx:Name="chart"Grid.Row="1"><charting:LineSeriesItemsSource="{Binding}"DependentValueBinding="{Binding Proficiency, Converter={StaticResource mult}, ConverterParameter=100.0}"IndependentValuePath="Num"Title="Proficiency"><charting:LineSeries.DependentRangeAxis><charting:LinearAxisOrientation="Y"Title="Proficiency"Minimum="0"Maximum="110.0"Interval="5.0"ShowGridLines="True"/></charting:LineSeries.DependentRangeAxis></charting:LineSeries><charting:Chart.Axes><!-- Shared horizontal axis --><charting:LinearAxisOrientation="X"Title="Number of questions"Interval="5"ShowGridLines="True"/></charting:Chart.Axes></charting:Chart>

My initials attempt have been focused on setting LineSeries.DataPointStyle.  For example, I tried this:

<charting:LineSeriesItemsSource="{Binding}"DependentValueBinding="{Binding Proficiency, Converter={StaticResource mult}, ConverterParameter=100.0}"IndependentValuePath="Num"Title="Proficiency"><charting:LineSeries.DataPointStyle><StyleTargetType="{x:Type charting:LineDataPoint}"><SetterProperty="Visibility"Value="Collapsed"/></Style></charting:LineSeries.DataPointStyle>



...hoping that the data point would simply disappear.  I do get a simple line when I do that, but instead of the nice gradient picked by the Chart by default, the line suddenly becomes orange.  And if I have a second line series, they both become orange in that case, making the legend fairly useless.

Any thoughts?

Thanks,

David Cater

Adding and Retrieving data from Combo Box

$
0
0

In the XAML I have this code:

<ComboBox x:Name="CurrencyCB" Header="Coin Face" FontSize="18" Height="70" Width="296" Margin="5,25,0,0" SelectionChanged="CurrencyCB_SelectionChanged"><ComboBoxItem><x:String>
                                Entry1</x:String></ComboBoxItem><ComboBoxItem><x:String>
                                Entry2</x:String></ComboBoxItem></ComboBox>

In the C# I have this code:

private void CurrencyCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Choice = CurrencyCB.SelectedValue.ToString();
        }

Then calling it in this code:

private void btn_random_Click(object sender, RoutedEventArgs e)
        {
            txt_response.Text = Choice;
        }
Just for reference, Choice is a String.

Popup Hidden on button click by Trigger

$
0
0

My Issues: How to open popup Hide , click on button By Trigger in WPF.


A.Acharya Feedback to us Develop and promote your apps in Windows Store Please remember to mark the replies as answers if they help and unmark them if they provide no help.

Create Custom Control Of Nested Grid In WPF

$
0
0

While creating a custom control of nested grid i am not able to bind child grid. Can any body help me into it?

Below code is a custom control code

Code Below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Collections;
using System.Windows.Controls.Primitives;
using System.Data;

namespace NestedCustomControl
{
    public class NestedGridControl : DataGrid
    {
        

        public override void BeginInit()
        {
            
            FrameworkElementFactory dtGrid = new FrameworkElementFactory(typeof(DataGrid));
            dtGrid.SetValue(DataGrid.ItemsSourceProperty, new Binding("setChildBind"));

            DataTemplate dttemp = new DataTemplate();
            dttemp.VisualTree = dtGrid;
           
            this.RowDetailsTemplate = dttemp; 

            base.BeginInit();
        }

        public BindingBase setChildBind
        {
            get
            {
                return (BindingBase)GetValue(SetChildBinding);
            }
            set
            {
                SetValue(SetChildBinding,value);
            }
        }

        

        public static readonly DependencyProperty SetChildBinding =
            DependencyProperty.Register("ChildBinding", typeof(BindingBase), 
            typeof(NestedGridControl), new FrameworkPropertyMetadata(OnChildGridSourceChange)); 

        private static void OnChildGridSourceChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
           

        }


        
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            DependencyObject dep = (DependencyObject)e.OriginalSource;

            //navigate up the tree
            while (dep != null && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
            {
                dep = VisualTreeHelper.GetParent(dep);
            }
            if (dep == null)
            {
                return;
            }

            DataGridCell dgc = dep as DataGridCell;

            if (dgc != null)
            {
                //navigate further up the tree
                while (dep != null && !(dep is DataGridRow))
                {
                    dep = VisualTreeHelper.GetParent(dep);
                }

                DataGridRow row = dep as DataGridRow;

                DataGrid dg = this as DataGrid;

                //row.Focusable = true;
                bool focused = row.Focus();
                FocusNavigationDirection focusDirection = FocusNavigationDirection.Down;
                FocusNavigationDirection focusDirectionUp = FocusNavigationDirection.Previous;
                TraversalRequest request = new TraversalRequest(focusDirection);
                TraversalRequest requestUp = new TraversalRequest(focusDirectionUp);
                UIElement elementWithFocus = Keyboard.FocusedElement as UIElement;

                if (e.Key == Key.Down)
                {
                    if (!e.Handled)
                    {
                        if (row.Background == Brushes.Gray && row.DetailsTemplate!=null)
                        {
                            row.DetailsVisibility = System.Windows.Visibility.Visible;
                        }
          
                        elementWithFocus.MoveFocus(request);

                        e.Handled = true;
                    }
                }
            }
        }
    }
}


Viewing all 18858 articles
Browse latest View live


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