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

Validation ErrorTemplate for Datepicker within UserControl

$
0
0

Hi

I have created a validation error template for a datepicker. It works but when I put the datepicker with the error template inside a usercontrol the validation doesn't trigger. Can someone help?

Here's my usercontrol xaml:

<UserControl x:Class="SandBox.LabelDatePicker"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Name="LDP"><Grid HorizontalAlignment="{Binding}"><Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><TextBlock x:Name="tbl" Text="{Binding ElementName=LDP, Path=LabelText}" Width="{Binding ElementName=LDP, Path=LabelWidth}" VerticalAlignment="Center"/><DatePicker x:Name="dp" Grid.Column="1" SelectedDate="{Binding ElementName=LDP, Path=SelectedDate, Mode=TwoWay}" VerticalAlignment="Center"><Validation.ErrorTemplate><ControlTemplate><DockPanel LastChildFill="True" ToolTip="{Binding ElementName=aep, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"><TextBlock DockPanel.Dock="Right" Foreground="Red" FontSize="14pt" Text="*" Margin="5,0,0,0" VerticalAlignment="Center" FontWeight="Bold"/><Border BorderBrush="Red" BorderThickness="1"><AdornedElementPlaceholder Name="aep"/></Border></DockPanel></ControlTemplate></Validation.ErrorTemplate></DatePicker></Grid></UserControl>


ListBox - Unable to cast object of type 'System.DateTime' to type 'System.String'.

$
0
0

Hello:

I have a listbox with DateTime objects.

I then have a method that I need to call and pass in the items from the listbox:

public bool copyFiles(List<string> datesProcess)

I attempt to call the method passing in the listbox:

if (obj.copyFiles(lstProcessDate.Items.Cast<string>().ToList()))
            { ...

I then receive the error:

Unable to cast object of type 'System.DateTime' to type 'System.String'.

How can I cast the DateTime items from the listbox to pass them in correctly as a list of string objects?

Thanks Before Hand

Binding error on XmlDataProvider (cannot bind to non-XML object)

$
0
0

Hi,

I have a problem on binding some controls to my XML.
My XAML is this (loaded at runtime):

<DataTemplate
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:EurocomCPS;assembly=EurocomCPS"><DataTemplate.Resources><local:StringToBoolConverter x:Key="StrToBoolConverter" /><local:StringToIntConverter  x:Key="StrToIntConverter" /><XmlDataProvider x:Key="dataProvider" XPath="func/parametri/param/BLOCKS"/></DataTemplate.Resources><Grid><Grid.RowDefinitions><RowDefinition Height="Auto" /><RowDefinition Height="Auto" /><RowDefinition Height="Auto" /><RowDefinition Height="Auto" /></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="100" /><ColumnDefinition Width="Auto" /></Grid.ColumnDefinitions><Label Grid.Row="0" Grid.Column="0" Content="ITEM 1:"/><Label Grid.Row="1" Grid.Column="0" Content="ITEM 2:"/><Label Grid.Row="2" Grid.Column="0" Content="ITEM 3:"/><TextBox  Grid.Row="0" 
              Grid.Column="1" 
              Text="{Binding XPath='//BLOCK[@id=1]/ITEMS/ITEM[@id=1]/@value'}" /><CheckBox Grid.Row="1" Grid.Column="1"><CheckBox IsChecked="{Binding XPath='//BLOCK[@id=1]/ITEMS/ITEM[@id=2]/@value',
                            Converter={StaticResource StrToBoolConverter}}"/></CheckBox><CheckBox Grid.Row="2" Grid.Column="1"><CheckBox IsChecked="{Binding XPath='//BLOCK[@id=1]/ITEMS/ITEM[@id=3]/@value',
                            Converter={StaticResource StrToBoolConverter}}"/></CheckBox></Grid></DataTemplate>

The xml file is this:

<func id="A29086"><parametri><param><BLOCKS max_count="2" write_id="49" read_req_id="47" read_rep_id="48" session_id="7"><BLOCK id="1" frame="1" framelen="61"><ITEMS max_count="14"><ITEM id="1" type="CHAR" size="1" value="0" /><ITEM id="2" type="CHAR" size="1" value="1" /><ITEM id="3" type="CHAR" size="1" value="0" />
            ...</ITEMS></BLOCK><BLOCK id="2" frame="1" framelen="61"><ITEMS max_count="14"><ITEM id="1" type="CHAR" size="1" value="0" /><ITEM id="2" type="CHAR" size="1" value="1" />
            ...</ITEMS></BLOCK></BLOCKS></param></parametri></func>
When running I get this error:
System.Windows.Data Error: 44 : BindingExpression with XPath cannot bind to non-XML object.; XPath='//BLOCK[@id=1]/ITEMS/ITEM[@id=1]/@value' BindingExpression:Path=/InnerText; DataItem='Tab' (HashCode=57706919); target element is 'TextBox' (Name=''); target property is 'Text' (type 'String') Tab:'EurocomCPS.Tab'
System.Windows.Data Error: 44 : BindingExpression with XPath cannot bind to non-XML object.; XPath='//BLOCK[@id=1]/ITEMS/ITEM[@id=2]/@value' BindingExpression:Path=/InnerText; DataItem='Tab' (HashCode=57706919); target element is 'CheckBox' (Name=''); target property is 'IsChecked' (type 'Nullable`1') Tab:'EurocomCPS.Tab'
System.Windows.Data Error: 44 : BindingExpression with XPath cannot bind to non-XML object.; XPath='//BLOCK[@id=1]/ITEMS/ITEM[@id=3]/@value' BindingExpression:Path=/InnerText; DataItem='Tab' (HashCode=57706919); target element is 'CheckBox' (Name=''); target property is 'IsChecked' (type 'Nullable`1') Tab:'EurocomCPS.Tab'

Where I wrong?

Conflicting InputBindings / InputBinding priority

$
0
0

Hi

how does wpf handle inputbindings that fire on the same gesture, key-combination?

My task is to let "Ctrl+A" select all items in a treeview. Unless the focus in on a textbox
where the name of one of the nodes is currently edited. In this case Ctrl+A should select
all text, but not change the items selection.

Can this done purely in XAML? It'd like to get rid of Key / Mouse down handlers.

The code i have in mind, but not yet implemented, is a little like the one below, just to demonstrate the "issue"

<ControlTemplate TargetType="TreeView"><Border><Border.InputBindings><KeyBinding Key="A" Modifiers="Control" Command="{TemplateBinding SelectAllItemsCommand}" /></Border.InputBindings>
        ...<HierarchicalDataTemplate DataType="{x:Type vm:BlaViewModelBase}" ItemsSource="{Binding Path=BlaChildren}"><TextBox><TextBox.InputBindings><KeyBinding Key="A" Modifiers="Control" Command="{Binding Path=SelectAllTextCommand}" /></TextBox.InputBindings></TextBox></HierarchicalDataTemplate>

Actually the TextBox is collapsed most of the time an the text is just readonly, displayed by a TextBlock. The TextBox becomes visible through a DataTrigger. When it's visible / enabled then also its Input binding for "Ctrl+A" shall override the Ctr+A-binding of the border.

So the target is to disable the "Outer" Ctrl+A-command when the textbox is editing.
How can it be done?

Thx,
Chris




Problem facing with implementation of MVVM

$
0
0

as i known about MVVM  "View Model" should not have Reference ofView or UI controls.

I have one requirement where i am facing problem with implementing in MVVM.

could you please help me in solving this..? it helps me a lot in understand as well.

Requirement :

I have a window which as Button and on click of Button i need to open a child window.

Problem:

1. I have created WPF window with a button.

2. On click of a button the Execute() method of Command is executed if i am right?[in view model i haveRelayCommand which implements ICommand with required methodsExecute() and it is binded with command property of Button] -->fireing of an event works fine.

3. Here the problem is that i need to open child window on click of a Button. but Child window can't access in View model because we know that it's View -- >can u please let me know how can i open child window on click of button.

becasue Execute() method written in View model and it is the event handler method. and i need to write code to open child window in the event handler method itself , am i correct?

Thanks,

How to edit a ListBox Item

$
0
0

I have a simple listbox of file names.   I have a button that I want to rename a file listed in the listbox.  

I have modified the default ListBoxItemStyle template and added a TextBox and made the visibility Collapsed.

<Grid><Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true"><ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/></Border><TextBox Name="EditableText" Visibility="Collapsed"/></Grid>

When I press my button I want to be able to edit the text of the selected ListBox item.  When you press enter on the textbox I want the item to be changed.

I was thinking I could use the Tag property of the ListBoxItem and set it to true to show the textbox but I can't figure out how to do that or how to hide the textbox when the textbox has lost focus.

Any help?


Jeff Davis

Apply RadioButton template in ListBoxItem

$
0
0

I need to change static content to dynamic content. Here is a snippet of my current code:

<Grid Grid.ColumnSpan="2" Grid.Row="1" HorizontalAlignment="Center"><RadioButton IsChecked="{Binding SelectedLetter, ConverterParameter='A', Converter={StaticResource InputLetterToBooleanConverter}, Mode=TwoWay}" 
                             Name="radioA" Content="A" HorizontalAlignment="Left" VerticalAlignment="Top" Width="48.5" Height="45" Style="{DynamicResource RadioButtonInputs}" FontSize="36" Padding="0" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{DynamicResource BrushLetterA}" Cursor="Hand"/><RadioButton IsChecked="{Binding SelectedLetter, ConverterParameter='B', Converter={StaticResource InputLetterToBooleanConverter}, Mode=TwoWay}" 
                             Name="radioB" Content="B" HorizontalAlignment="Left" Margin="53.5,0,0,0" VerticalAlignment="Top" Width="48.5" Height="45" Style="{DynamicResource RadioButtonInputs}" FontSize="36" Padding="0" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{DynamicResource BrushLetterB}" Cursor="Hand"/><RadioButton IsChecked="{Binding SelectedLetter, ConverterParameter='C', Converter={StaticResource InputLetterToBooleanConverter}, Mode=TwoWay}" 
                             Name="radioC" Content="C" HorizontalAlignment="Left" Margin="107,0,0,0" VerticalAlignment="Top" Width="48.5" Height="45" Style="{DynamicResource RadioButtonInputs}" FontSize="36" Padding="0" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{DynamicResource BrushLetterC}" Cursor="Hand"/><RadioButton IsChecked="{Binding SelectedLetter, ConverterParameter='D', Converter={StaticResource InputLetterToBooleanConverter}, Mode=TwoWay}" 
                             Name="radioD" Content="D" HorizontalAlignment="Left" Margin="160.5,0,0,0" VerticalAlignment="Top" Width="48.5" Height="45" Style="{DynamicResource RadioButtonInputs}" FontSize="36" Padding="0" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{DynamicResource BrushLetterD}" Cursor="Hand"/></Grid>

And here is what it generates:

You see, there are always 4 letters (A, B, C, D), however, now I have to change this code to support dynamic number of letters, from A to D. So could be A B, or A B C, or just A. The maximum letter is D.

So, I thought to use ListBox (because user can selected a letter) and a ValueConverter to proper choose the Foreground Brush depending on the letter. That's not the problem.

The problem is that I can't use the RadioButtons anymore. I need to use some other control right? In the same time, I need the stylish of the RadioButton: depth, mouse over. How can I apply the style on the Item of the ListBox:

Here's the style:

<Style x:Key="RadioButtonInputs" TargetType="{x:Type RadioButton}"><Setter Property="BorderThickness" Value="1"/><Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/><Setter Property="HorizontalContentAlignment" Value="Center"/><Setter Property="VerticalContentAlignment" Value="Center"/><Setter Property="Padding" Value="1"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type RadioButton}"><Grid x:Name="grid" Margin="0"><VisualStateManager.VisualStateGroups><VisualStateGroup x:Name="CommonStates"/><VisualStateGroup x:Name="FocusStates"/><VisualStateGroup x:Name="CheckStates"><VisualState x:Name="Checked"/><VisualState x:Name="Unchecked"/><VisualState x:Name="Indeterminate"/></VisualStateGroup><VisualStateGroup x:Name="ValidationStates"/></VisualStateManager.VisualStateGroups><Rectangle x:Name="normal" RadiusY="1.167" RadiusX="1.167" Width="Auto" Height="Auto" Margin="0" Stroke="{DynamicResource BrushToggleButtonStrokeNormal}" HorizontalAlignment="Stretch" Grid.Row="0" Grid.ColumnSpan="1" Grid.Column="0" Grid.RowSpan="1" StrokeThickness="2" d:IsEffectDisabled="True" Fill="{DynamicResource BrushToggleButtonFill}"/><Rectangle x:Name="mouse_over" RadiusY="1.167" RadiusX="1.167" Width="Auto" Height="Auto" Margin="0" Stroke="#00000000" HorizontalAlignment="Stretch" Grid.Row="0" Grid.ColumnSpan="1" Grid.Column="0" Grid.RowSpan="1" StrokeThickness="4" Visibility="Hidden" Fill="{DynamicResource BrushToggleButtonFill}"><Rectangle.Effect><ee:BloomEffect BloomIntensity="1" BaseSaturation="1" BaseIntensity="1" BloomSaturation="1" Threshold="0"/></Rectangle.Effect></Rectangle><Rectangle x:Name="clicked" RadiusY="1.167" RadiusX="1.167" Width="Auto" Height="Auto" Margin="0" Stroke="#00000000" HorizontalAlignment="Stretch" Grid.Row="0" Grid.ColumnSpan="1" Grid.Column="0" Grid.RowSpan="1" StrokeThickness="4" Visibility="Hidden" Fill="{DynamicResource BrushToggleButtonFill}"><Rectangle.Effect><ee:ColorToneEffect DarkColor="Black" Desaturation="0.41" ToneAmount="0.48" LightColor="Black"/></Rectangle.Effect></Rectangle><Label Content="{TemplateBinding Content}" VerticalAlignment="Center" HorizontalContentAlignment="Center" Foreground="{TemplateBinding Foreground}" FontSize="{TemplateBinding FontSize}" FontFamily="{DynamicResource FontFamily}" HorizontalAlignment="Center" Height="38.93" Margin="13.03,-3.93,11.75,10" Padding="0,0,0,-1" VerticalContentAlignment="Center"/></Grid><ControlTemplate.Triggers><Trigger Property="IsChecked" Value="true"><Setter Property="Stroke" TargetName="normal" Value="{DynamicResource BrushBorderBlueButton2}"/></Trigger><Trigger Property="IsPressed" Value="True"><Setter Property="Visibility" TargetName="clicked" Value="Visible"/></Trigger><Trigger Property="IsMouseOver" Value="True"><Setter Property="Visibility" TargetName="mouse_over" Value="Visible"/></Trigger><Trigger Property="IsEnabled" Value="false"><Setter Property="Opacity" TargetName="grid" Value="{DynamicResource DoubleOpacity}"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>

Here's the new (not yet all implemented) ListBox:

<Grid Grid.ColumnSpan="2" Grid.Row="1" HorizontalAlignment="Center"><ListBox ItemsSource="{Binding Inputs}"
                         Background="Transparent" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" BorderThickness="0"><ItemsControl.ItemTemplate><DataTemplate><RadioButton Margin="1" Content="B" Width="48.5" Height="45" Style="{DynamicResource RadioButtonInputs}" FontSize="36" Padding="0" Background="{x:Null}" BorderBrush="{x:Null}" Foreground="{DynamicResource BrushLetterB}" Cursor="Hand"/></DataTemplate></ItemsControl.ItemTemplate><ListBox.ItemsPanel><ItemsPanelTemplate><UniformGrid Rows="1" Columns="4" /></ItemsPanelTemplate></ListBox.ItemsPanel></ListBox></Grid>
Also, which control do I use instead of RadioButton?


Take a look at WPF FlashMessage
About.me



PropertyChanged Null when not visible

$
0
0

hi,

I am having issue with a Collection shown in a Listview giving null on PropertyChanged when the item is not visible in the UI

Here is what i am trying to do.

I have a Checkbox in the list view that is registered to Checked

<ListView Name="lvSuites" 
                  Grid.Row="3" Grid.ColumnSpan="2"
                  Margin="10,10,10,10"
                  ItemsSource="{Binding Path=SuiteList, Mode=TwoWay}"
                  Background="{StaticResource PressedBrush}"
                  BorderBrush="{StaticResource SolidBorderBrush}" Foreground="Black"><ListView.View><GridView><GridViewColumn Width="Auto"><GridViewColumn.CellTemplate><DataTemplate><CheckBox IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" Tag="{Binding Path=Name, Mode=TwoWay}" Checked="CheckBoxChecked" Unchecked="CheckBoxUnchecked"/></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Width="40" Header="#" ><GridViewColumn.CellTemplate><DataTemplate><TextBlock TextAlignment="Center" Text="{Binding Path=TestNumber, Mode=TwoWay}"/></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Width="300" Header="Suite"><GridViewColumn.CellTemplate><DataTemplate><TextBlock TextAlignment="Left" Text="{Binding Path=Name, Mode=TwoWay}"/></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn></GridView></ListView.View></ListView>

When i call

private void ListSuiteAllMouseUp(object sender, MouseButtonEventArgs e)
        {
            foreach (var suite in ((ViewModel)DataContext).SuiteList)
            {
                suite.IsChecked = true;
            }
        }

PropertyChanged is null for the items that are not visible in the Scrollview of the Listview, but the ones that are visible call Checked of the checkbox

    public class Suite : INotifyPropertyChanged
    {
        private bool ischecked;
        private string name;
        private int testNumber;

        public Suite()
        {
            IsChecked = false;
        }

        public bool IsChecked
        {
            get { return ischecked; }
            set
            {
                ischecked = value;
                OnPropertyChanged("IsChecked");
            }
        }

        public int TestNumber
        {
            get { return testNumber; }
            set
            {
                testNumber = value;
                OnPropertyChanged("TestNumber");
            }
        }

        public string Name
        {
            get { return name; }
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;

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

and i have my ViewModel 

DataContext = ViewModel();

private void CheckBoxChecked(object sender, RoutedEventArgs e)
        {
            //Do Something
        }


Can anyone help me get the PropertyChanged to not be null even for items that arnt visible in the ListView bc they are farther down the ScrollView becuase i want Checked to be called if i changed IsChecked property or if the user actually checks it. if i scroll down the list view and try setting IsChecked= true it works for the items that are now visible. It seems like PropertyChanged doesnt get attached till the object is rendered.



Why doesn't Textbox support Multibinding on IsEnabled?

$
0
0

Hi all,

I have searched far and wide, but I can't find an answer to what should be a simple question....

Given that I have a converter with this signature:

 
public class multiBoolConverter : IMultiValueConverter
	{
		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) 
{
...
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return null;
}

I am trying to implement a textbox that is bound to a value and has it's IsEnabled property bound to 2 values using the above multiConverter.

I have found tons of examples, but none that work with this situation (or at least close enough that I can figure it out.)

Here is the basic textbox:

<TextBox Text = "{Binding thing_no}"><Textbox.IsEnabled><MultiBinding Converter="{StaticResource multiBoolConverter}"
            ConverterParameter="and"><Binding Path="val1" /><Binding Path="val2"/></MultiBinding></Textbox.IsEnabled></TextBox>

And in the resource section of the xaml form I have:

<src:multiBoolConverter x:Key="multiBoolConverter" />

Where src: is tied to the namespace that holds the convert class defined above.

The problem is that when I try this, I get an error that "The attachable property 'IsEnabled' was not found in type 'TextBox'.

Now we all know that Textbox does support IsEnabled (I use it a bunch of other places).  But in this one case, I need to look at 2 bool values in the model, whereas in all the other cases, I just need one.

So the converter code looks at the 2 values and returns true/false.  I pass a parameter so I can specify if I need the values to be compared with an AND or OR.

Any idea what silly little thing I am missing that is causing it not to behave?

Thanks!


me (and yes, I DO mark correct answers)

After changing My Settings Name on application settings setup panel, the user.config file disappears or has only 3-5 lines and the application settings operation stop working in its totality

$
0
0

My original (wrong) settings name was "User'sOption" when I replaced the default name "Settings1".settings. And  I quickly decided that I was wrong because no apostrophe has everbeen allowed in naming in the MS world so far as I could remember.

So I rename it to "UserOption".settings in the VS2012 Express C# editor. I got, of course, the warning message of "not reusable" but decided to do it anyway. The name of the designer.cs file did not change accordingly. Instead, it changed to UserOption1 without my intervention. So I thought I could live with it although it was wrong by adding an extra "1" to it. Then the big surprise occurred to me, i.e., the saving-in-user.config refused to work and value-changes in properties( all five int-type indices under the user-scope with default values of five 0's) were ignored by the operation altogether. (It never worked because this was my first use of the application settings class of MS WPF System.Windows.)

I then checked the user.config and found four of folders under "Hewlett Packard Company" with folder-names like XXX.exe.vhost.config.hashcode... or simply XXX.exe.plus hashcode..(wherein XXX stand for my namespace or application name.) I was surprised to have found so many folders. The user.config had only 3-5 lines in XML file and no any property value nor term concerning serialization was ever mentioned.  Moreover, after I deleted the settings in preparation to a clean run, I found to my dismay that the user.config file disappeared without a trace.

I've such a bad luck until today that no rejoice has ever come to me for the application settings operation being successful at least once from the very beginning. The only satisfaction I got was that there was not a single letter coming up to show me in terms of exceptions. That means the problem is not due to my lack of skill and ability in coding :)

I have sought for the past couple of days for help and come up with none. I hope my Microsoft colleagues would have some ideas as to how to remedy the issue (possibly due to my mistake in naming the wrong settings-name in the first place.)

Thank you in advance.

Mark

PS - I did click the synchronize button once although without knowing it would "remove the user's configuration file where the application saves changes to user settings." Also, if I'm not mistaken, the application settings are based on the windows form architecture and are quite old.


Add and manage Checkboxcolumn to the start of a bound datagrid

$
0
0

Hi,

    I have a DataGrid which is bound to a List<X>. I am looking for is add a column at the start of the DataGrid & if that checkbox is selecetd then only retrieve the values of the row, else ignore it. Similarly, when I set the ItemSource of the DataGrid, for each row added the 1st cols checkbox should be checked.

   I have not written any code for retrieving data from datagrid by checking the 1st col, as all rows got to be added to the List. When I set the ItemSource I am not able to check mark the 1st checkbox col of that row. The code is :

XML -

<DataGrid AutoGenerateColumns="False" Name="dgvSiSelection" BorderBrush="#FFB7B39D" Background="LightYellow" RowBackground="LightGray" AlternatingRowBackground="#FFFFFFF5" BorderThickness="10" FontSize="13" FontFamily="Segoe UI" CanUserAddRows="False"><DataGrid.Columns><DataGridCheckBoxColumn Binding="{Binding BoolProperty, Mode=TwoWay}"/><DataGridTextColumn Header="" Binding="{Binding SiHeader}" MinWidth="108" IsReadOnly="True"/><DataGridTextColumn Header="Number of Chemicals" Binding="{Binding S_NumberOfCases}" /><DataGridTextColumn Binding="{Binding S_Value1}" ><DataGridTextColumn.Header><Grid><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><TextBlock Grid.Column="1" Text="Value1"/><CheckBox Name="chkNValue1"  Grid.Column="0" Width="16" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridColumn}}, Path=DataContext.AllItemsAreChecked}" /></Grid></DataGridTextColumn.Header></DataGridTextColumn><DataGridTextColumn Binding="{Binding S_Value2}" ><DataGridTextColumn.Header><Grid><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><TextBlock Grid.Column="1" Text="Value2"/><CheckBox Name="chkNValue2"  Grid.Column="0" Width="16" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridColumn}}, Path=DataContext.AllItemsAreChecked}" /></Grid></DataGridTextColumn.Header></DataGridTextColumn></DataGrid.Columns></DataGrid></GroupBox>
    public class SIData
    {
        public string SiHeader { get; set; }
        public string S_NumberOfCases { get; set; }
        public int S_Value1 { get; set; }
        public int S_Value2 { get; set; }
    }


        private void LoadGUI()
        {
            List<SIData> sd = mw.xlsImpExp.GetStep5SiList();

            dgvSiSelection.ItemsSource = sd;

            // SI Grid - Check the ValueX checkbox on header - if any of the object contains Value1 or Value2 then check mark that respective cheader checkbox
            for (int i = 0; i < sd.Count; i++)
            {
                SIData s = sd[i];

                if (s.S_Value1 > 0)
                    chkNValue1.IsChecked = true;
                if (s.S_Value1 > 0)
                    chkNValue2.IsChecked = true;
            }

           // What code do I write to check mark the checkbox 1st col of rows that are entered ?

            return;
        }

Lets say the List has 2 objects, so in dataGrid 2 rows will be added. Now, I want to cehckmark the 1st col i.e. the checkbox of both rows. How do I achieve that ?

Secondly, I was also wondering, is their any better or easy code to set the checkmark of Value1 & Value2 if any of the rows have values of respective field greater than 0. I mean, if 1st row have "4" in S_Value1 & 2nd row has "0", then Value1 checkbox chkNValue1 should be clicked. If all the rows have value as "0" in S_Value2 field, then the chkNValue2 checkbox should not be selected.

Any help is appreciated. Please help me with this.

Thanks


Thanks
If you find any answer helpful, then click "Vote As Helpful" and if it also solves your question then also click"Mark As Answer".

ObservableCollection DependencyProperty for new Custom FrameworkElement

$
0
0

Hi,


I want to create custom control which is simply occurs a grid and contains rectangle elements. I want to make databinding for the rectangle elements. Therefore I create a custom class for my grid and has a dependency property for Rectangle objects.


 public class MyGrid : Grid
 {
        public static readonly DependencyProperty TimeInformationContentProperty =
              DependencyProperty.Register("TimeInformationContent",
            typeof(ObservableCollection<Rectangle>),
            typeof(MyGrid),
            new PropertyMetadata(new ObservableCollection<Rectangle>() )
            );

        public ObservableCollection<Rectangle> TimeInformationContent
        {
            get { return (ObservableCollection<Rectangle>)GetValue(TimeInformationContentProperty); }
            set { SetValue(TimeInformationContentProperty, value); }
        }
}


Now I create a new UserControl ie. TimeControl.cs, and this control has the same DependencyProperty above. In XAML part i write:

<main:MyGrid TimeInformationContent="{Binding Path=TimeInformationContent, ElementName= Root_Part}" />

for databinding.

Then I want to use this UserContol in the MainWindow and i write this:

<Window.DataContext><main:ViewModel /></Window.DataContext><Grid><Grid.RowDefinitions><RowDefinition Height="auto" /><RowDefinition Height="*" /></Grid.RowDefinitions><main:TimeControl TimeInformationContent="{Binding RectangleContent, Mode=TwoWay}" Height="50" /></Grid>

which in ViewModel part i have an ObservableCollection for the rectangles.

Here is the questin: this code does not work.

Is there a simple mistake? or the concept for this scenario is totaly wrong?

King Regards



Different sized items in an ItemsControl retaining required width only

$
0
0

Hi, I have a problem with what I thought would not be that complicated, but I have now spent a few hours stuck with what to try next.

I have a sample of the following at https://dl.dropboxusercontent.com/u/30760237/ItemsControlWidth.zip, which contains the following XAML..

<Window x:Class="ItemsControlWidth.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"><Grid Width="200"><!--<ScrollViewer Margin="20">--><ItemsControl ItemsSource="{Binding Data}" HorizontalContentAlignment="Left" Width="Auto"><ItemsControl.ItemTemplate><DataTemplate><!--<Border  Margin="5" Background="LightGreen"  CornerRadius="5">--><Grid Width="Auto" Background="Brown"><Grid.RowDefinitions><RowDefinition /><RowDefinition/></Grid.RowDefinitions><TextBlock Background="Pink"  Width="Auto" Text="{Binding Key}"/><TextBlock Width="Auto"  Background="Pink"  Grid.Row="1" Text="{Binding Value}"/></Grid><!--</Border>--></DataTemplate></ItemsControl.ItemTemplate></ItemsControl><!--</ScrollViewer>--></Grid></Window>

Basically, I have an ItemsControl, using an items template of a grid with 2 TextBlocks, where each item may have different sized text. What I am after is that each item is NOT stretched to the width of the Items control. However, as can be seen in the attached example, they are always stretched. If it worked as I wanted, I would see different sized items in the items control

I would have thought that setting the HorizontalContentAlignment on the items control to something other than stretch on the would stop this, but unfortunatley is doesn't. I removed my ScollViewer, and surrounding border (and colored the elements to see them), but they still all stretch.

Does anyone know a way around this? Can I have each item just wide enough to fix it's contents (ie the text and any margins etc)

Thanks in advance for any help.

Regards, Peter

Adding Custom Fonts to System crashes WPF application which uses SystemFonts.

$
0
0

Hi,

I 'm using a control like Combobox has the list of SystemFonts in WPF. This worked fine for me until my installation of new font.After installing new font Application runs,But when i click the drop down of ComboBox application get crashed or sometimes it shows the list but crashes after selecting that particular font ,With a inner exception of

"Input file or data stream does not conform to the expected file format specification".

I've read your forum titled "wpf application crashes after setting label font family to a bad one "

But i couldn't really get it.

Can you help me to know what am i  doing wrong? or give me workaround to solve this.

looking forward to your reply.

Thanks,

Muthukumar A

S/W Engineer (junior)

Common dialog for selecting a folder - where is it?

$
0
0
Hi,
this must be a very easy one, but I just don't find it: where is the common dialog for letting a user select a folder? I looked at Microsoft.Win32.OpenFileDialog, but that's for selecting files... Surely, there must be one for selecting a folder?
Thanks,
Koen

Save draw images xml with .jpg,.png and etc

$
0
0
 draw images in drawing canvas panel to save .jpg, .png and etc  save this images are not open in photoshop software anybody help me..

Overflow or underflow in the arithmetic operation + unmanaged code

$
0
0

I know there are a few threads regarding this issue but no one seems to fix the real problem. Most threads are also very old.

I'm using WPF with a datagrid attached to a background updated ViewModel. A 3 part unmanaged COM DLL fires events which updates the ViewModel. 

Some installations seems to run steady and other crashes every 5 minutes.

How do I find and eliminate the reason for these crashes?

The stacktrace doesn't say much.

CurrentDomain_UnhandledException System.ArithmeticException: Overflow or underflow in the arithmetic operation.
   at System.Double.Equals(Object obj)
   at System.Object.Equals(Object objA, Object objB)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.StyleHelper.ApplyStyleOrTemplateValue(FrameworkObject fo, DependencyProperty dp)
   at System.Windows.StyleHelper.InvalidateContainerDependents(DependencyObject container, FrugalStructList`1& exclusionContainerDependents, FrugalStructList`1& oldContainerDependents, FrugalStructList`1& newContainerDependents)
   at System.Windows.StyleHelper.DoThemeStyleInvalidations(FrameworkElement fe, FrameworkContentElement fce, Style oldThemeStyle, Style newThemeStyle, Style style)
   at System.Windows.StyleHelper.UpdateThemeStyleCache(FrameworkElement fe, FrameworkContentElement fce, Style oldThemeStyle, Style newThemeStyle, Style& themeStyleCache)
   at System.Windows.FrameworkElement.OnThemeStyleChanged(DependencyObject d, Object oldValue, Object newValue)
   at System.Windows.StyleHelper.GetThemeStyle(FrameworkElement fe, FrameworkContentElement fce)
   at System.Windows.FrameworkElement.UpdateThemeStyleProperty()
   at System.Windows.FrameworkElement.OnInitialized(EventArgs e)
   at System.Windows.FrameworkElement.TryFireInitialized()
   at System.Windows.FrameworkElement.EndInit()
   at System.Windows.FrameworkElementFactory.InstantiateTree(UncommonField`1 dataField, DependencyObject container, DependencyObject parent, List`1 affectedChildren, List`1& noChildIndexChildren, FrugalStructList`1& resourceDependents)
   at System.Windows.FrameworkElementFactory.InstantiateTree(UncommonField`1 dataField, DependencyObject container, DependencyObject parent, List`1 affectedChildren, List`1& noChildIndexChildren, FrugalStructList`1& resourceDependents)
   at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
   at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
   at System.Windows.FrameworkElement.ApplyTemplate()
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at Microsoft.Windows.Themes.ClassicBorderDecorator.MeasureOverride(Size availableSize)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.Controls.Control.MeasureOverride(Size constraint)
   at System.Windows.Controls.TextBox.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at MS.Internal.Helper.MeasureElementWithSingleChild(UIElement element, Size constraint)
   at System.Windows.Controls.ContentPresenter.MeasureOverride(Size constraint)
   at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   at System.Windows.UIElement.Measure(Size availableSize)
   at System.Windows.ContextLayoutManager.UpdateLayout()
   at System.Windows.UIElement.UpdateLayout()
   at System.Windows.Controls.DataGridCell.BeginEdit(RoutedEventArgs e)
   at System.Windows.Controls.DataGrid.OnExecutedBeginEdit(ExecutedRoutedEventArgs e)
   at System.Windows.Controls.DataGrid.OnExecutedBeginEdit(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.CommandBinding.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.CommandManager.ExecuteCommandBinding(Object sender, ExecutedRoutedEventArgs e, CommandBinding commandBinding)
   at System.Windows.Input.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings, Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
   at System.Windows.Input.CommandManager.FindCommandBinding(Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
   at System.Windows.Input.CommandManager.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.UIElement.OnExecutedThunk(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler, Object target)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.RoutedCommand.ExecuteImpl(Object parameter, IInputElement target, Boolean userInitiated)
   at System.Windows.Input.RoutedCommand.Execute(Object parameter, IInputElement target)
   at System.Windows.Controls.DataGrid.BeginEdit(RoutedEventArgs editingEventArgs)
   at System.Windows.Controls.DataGridColumn.BeginEdit(InputEventArgs e, Boolean handled)
   at System.Windows.Controls.DataGridTextColumn.OnInput(InputEventArgs e)
   at System.Windows.Controls.DataGridCell.OnTextInput(TextCompositionEventArgs e)
   at System.Windows.UIElement.OnTextInputThunk(Object sender, TextCompositionEventArgs e)
   at System.Windows.Input.TextCompositionEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.TextCompositionManager.UnsafeCompleteComposition(TextComposition composition)
   at System.Windows.Input.TextCompositionManager.PostProcessInput(Object sender, ProcessInputEventArgs e)
   at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(ProcessInputEventHandler postProcessInput, ProcessInputEventArgs processInputEventArgs)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.TextCompositionManager.UnsafeStartComposition(TextComposition composition)
   at System.Windows.Input.TextCompositionManager.PostProcessInput(Object sender, ProcessInputEventArgs e)
   at System.Windows.Input.InputManager.RaiseProcessInputEventHandlers(ProcessInputEventHandler postProcessInput, ProcessInputEventArgs processInputEventArgs)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndKeyboardInputProvider.ProcessTextInputAction(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
   at System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(MSG& msg, Boolean& handled)
   at System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage(MSG& msg, Boolean& handled)
   at System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.Run()
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()

DataGridColumn Width Binding

$
0
0

I have tried binding the width of a DataGridColumn with that of another control or with a Property in ViewModel but it doesn't seem to work. Look forward for help.

Requirement:

To hide the empty column that shows up at the end of the data grid, I am trying to increase the width of the last column in the datagrid on resizing the window instead of setting its width to * so that horizontal scroll bar always appears and other columns can be resized.


Ramakrishna


Adorner layer lost after selecting different tabitem (speaking of validationerror adorner)

$
0
0

 

Everyone,

 

I have a simple window with a TabControl and two TabItems.

 

The TextBoxs are wired up using the new 3.5 IDataErrorInfo validation and it works great!

 

Problem is, if I am on TabItem One, that is displaying several validationerror adorners, and then switch to TabItem Two and then switch back to TabItem One, all the validationerror adorners are now gone.  The validationerrors still exists, just no visual clues.

 

It took me a while to figure out that the adorner layer was being erased when the TabControl changes TabItems.

 

Is there a way to make this work without refeshing all the databindings using the UpdateSource method?

 

Thank you for your help.

 

 

DataGrid and persisting on cell lost focus

$
0
0

I need to persist the value of a cell when the user leaves it. This sounds like a quite normal use case but apparently this isn't very Google’able.

I have a working solution using the DataGrid_CellEditEnding and delaying  the persisting logic on the Dispatcher since the model hasn’t been updated yet.

There must be other ways to do this!?

privatevoid DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)

{

   Action action = () =>

    {

       var row = e.Row.ItemasMyRow;

        row.RootModel.Save(row);

    };

   //TODO : WTF! :)

   //we need to execute this on the gui queue, since the viewmodel has not been updated yet!

   //http://stackoverflow.com/questions/2094615/textchanged-lostfocus-etc-event-for-datagridtextcolumn

    Dispatcher.BeginInvoke(action,DispatcherPriority.ContextIdle);

}

Viewing all 18858 articles
Browse latest View live


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