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

MVVM and Commands

$
0
0

Hi to all,

Well, I followed the rules I pieced together on creating commands and I created a ScanCommand class that implements the ICommand intefrace.  In my ViewModel's constructor I attach a new instance of ScanCommand to my ScanCmd property, ie

(Inside my ViewModel constructor I have the following:)

ScanCmd = new ScanCommand(this);

What I notice is that this ScanCommand instance has its Execute method called before I hit the Scan button? Is the Execute method called upon construction of my command if CanExecute is set to true?  Should my CanExecute method be set to false upon construction of my Command?

Thanks


MarcinMR


C# WPF multithreading cannot return the actual value from Dispatcher.BeginInvoke in VS2013

$
0
0

I would like to get the return value from a thread in C# VS2013 WPF.

The code is:

    int t = 0;
    Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
        t = myFucntion()
    ));
    return t;

Why t is always 0 and not return the actual value ?
The solution here does not work for me.

http://stackoverflow.com/questions/1394028/wpf-dispatcher-invoke-return-value-is-always-null

If I used

     Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal,newAction(()=> t = myFunction()));

I got error: An unhandled exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll. Additional information: Cannot perform this operation while dispatcher processing is suspended.

In WPF two tabs gets selected if I run following application on Window's 10 machine.

$
0
0

f I run below application on window's 7 system it works fine but if i run it on window's 10
machine two tabs 'tab 1 ' and 'tab 2' gets selected after clicking 'Add' button.
Window's 10 have .net 4.6 framework installed. I am never able to select 'tab 1' again.

namespace TabControlTest { using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Input; public class MainWindowViewModel :INotifyPropertyChanged { private TabItem _selectedItem; private TabItem _homePageTabItem; private ObservableCollection<TabItem> _tabItems; private IList<TabItem> _tabBackingList; public MainWindowViewModel() { _homePageTabItem = new TabItem { Header = "Tab 1", Content = "Tab 1 Content", IsSelected = true, IsChecked = true }; _tabBackingList = new List<TabItem> { _homePageTabItem }; TabItems = new ObservableCollection<TabItem>(_tabBackingList); AddCommand = new RelayCommand(AddTabs); } public ICommand AddCommand { get; private set; } public ObservableCollection<TabItem> TabItems { get { return _tabItems; } set { if (_tabItems != value) { _tabItems = value; OnPropertyChanged(); } } } public TabItem SelectedItem { get { return _selectedItem; } set { if (_selectedItem != value) { _selectedItem = value; OnPropertyChanged(); } } } private void AddTabs(object param) { _tabBackingList.Clear(); _tabBackingList.Add(_homePageTabItem); var item2 = new TabItem { Header = "Tab 2", Content = "Tab 2 Content", IsSelected = true, IsChecked = true }; var item3 = new TabItem { Header = "Tab 3", Content = "Tab 3 Content", IsSelected = false }; _tabBackingList.Add(item2); _tabBackingList.Add(item3); TabItems = new ObservableCollection<TabItem>(_tabBackingList); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } namespace TabControlTest { using System; using System.Windows.Input; public class RelayCommand : ICommand { private readonly Predicate<object> _canExecute; private readonly Action<object> _execute; public RelayCommand(Action<object> execute) { _execute = execute; } public bool CanExecute(object parameter) { if (_canExecute == null) return true; return _canExecute(parameter); } public void Execute(object parameter) { _execute(parameter); } public event EventHandler CanExecuteChanged; } } namespace TabControlTest { using System.ComponentModel; using System.Runtime.CompilerServices; public class TabItem : INotifyPropertyChanged { private bool _isSelected; private bool _isChecked; public string Header { get; set; } public string Content { get; set; } public bool IsSelected { get { return _isSelected; } set { if (_isSelected != value) { _isSelected = value; OnPropertyChanged(); } } } public bool IsChecked { get { return _isChecked; } set { if (_isChecked != value) { _isChecked = value; OnPropertyChanged(); } } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } } } namespace TabControlTest { using System.Windows; /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new MainWindowViewModel(); } } }


<Window x:Class="TabControlTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:tabControlTest="clr-namespace:TabControlTest"
                     xmlns:uxc="http://schemas.thermofisher.com/2013/UXLibrary/Controls"

        Title="MainWindow" Height="350" Width="525"><Grid><Grid.RowDefinitions><RowDefinition Height="Auto"></RowDefinition><RowDefinition Height="*"></RowDefinition></Grid.RowDefinitions><Button Content="Add" Margin="5" Grid.Row="0" Width="100" HorizontalAlignment="Left" Command="{Binding AddCommand}" ></Button><TabControl  Margin="5" Grid.Row="1" SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding TabItems}" ><TabControl.ItemContainerStyle><Style TargetType="TabItem"><Setter Property="Header" Value="{Binding Header}"/><Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"></Setter></Style></TabControl.ItemContainerStyle><TabControl.ContentTemplate><DataTemplate DataType="{x:Type tabControlTest:TabItem}"><Button Content="{Binding Content}"></Button></DataTemplate></TabControl.ContentTemplate></TabControl></Grid></Window>


UI not updated with value change

$
0
0

I have a WPF application, with 2 user controls that have same combo boxes.

     
             <ComboBox x:Name="cbxTest" Grid.Row="0" HorizontalAlignment="Left" Margin="297,101,0,-34" VerticalAlignment="Top" Width="262"  ItemsSource="{Binding TestLst, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged
 }" DisplayMemberPath="Name" SelectedValuePath="ID"
SelectedItem="{Binding TestSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Height="22"  SelectionChanged="cbxTest_SelectionChanged"/> private ObservableCollection<TestData> _testList; public ObservableCollection<TestData> TestLst        {            get { return _testList; }            set            {                _testList = value;                NotifyPropertyChanged("TestLst");            }        } private TestData _testSelected; public TestData TestSelected        {            get { return _testSelected; }            set { _testSelected = value;            NotifyPropertyChanged("TestSelected");            }        }

When I load the page for the first time the selected value is set properly. However, if I go to the same page again, even though the TestSelected object has the correct value, it is not selected in the combo box. I checked the output box, there is no error, The property value is set correctly but I am not able to figure out what I am missing here. 


Change DataGridTemplateColumn based on value

$
0
0

Hi guys,

I have a PowerShell script which is getting info about hardware failures into array. I want to add GUI to make it more usable. I have several columns, one of which is Ticket, which contains ticket number in bug tracker or "N/A" if ticket wasn't found. So array looks like:

ServerIssueTicket

Server1Dimm-degradedDCOps-1234

Server2Dimm-degradedN/A

I want to create a button which will send a request to bug tracker and create an issue, so basically when clicked it should read info from all cells in the same row about failed server and send a request. I'm already have a code to create a request, one thing I'm struggling is how to change cell value type from text to button. Another requirement that it should be done programmatically (no XAML). I found pretty nice solution, but as not being a true programmer and absolutely new to WPF, quite hard to adopt to my needs, here it is - solution

Best regards, Sergey


MCSE, MCITP, CCNA Security Subscribe to my blog at http://sypalo.com


Drawing brush auto-clipping my geometry drawing

$
0
0

Hello everyone,

I have, as far as I imagine, a fairly simple problem - I am using a geometry drawing to represent an arrow, but it is being clipped to its outermost points for some unknown reason. I thought that if I have the viewport set to 0,0,1,1 and the outermost point at Y=0.8, it should render accordingly. Here is my problem:

<DrawingBrush x:Key="normalReaction" Stretch="Uniform"><DrawingBrush.Drawing><DrawingGroup><GeometryDrawing><GeometryDrawing.Pen><Pen Brush="White" Thickness="0.08"/></GeometryDrawing.Pen><GeometryDrawing.Geometry><GeometryGroup><LineGeometry StartPoint="0,0.5" EndPoint="1,0.5"/><PathGeometry><PathFigure IsClosed="False" IsFilled="False" StartPoint="0.5,0.2"><PathFigure.Segments><LineSegment Point="1,0.5"/><LineSegment Point="0.5,0.8"/></PathFigure.Segments></PathFigure></PathGeometry></GeometryGroup></GeometryDrawing.Geometry></GeometryDrawing></DrawingGroup></DrawingBrush.Drawing></DrawingBrush>

This XML code is not giving me an arrow that's in the center of the drawing area, but it resizes to fit the bounding box. I realize this is intended behaviour if you use the Uniform stretching mode, but I would like the brush to stretch it uniformly, as a whole, not just the clipped brush. Here is the faulty result:

The arrow should begin and end where I specified, that is 0.2 of the container height and end at 0.8 of the container height.

How can I achieve this?



Best architecture model for application which process heavy data

$
0
0

Hello,

Requirement of  WPF application is to read  big files of size more than 2 GB and display it  in UI as a data series graph. I have used a approach to read chunks of file say 100 KB & process the raw data and display in UI, instead of reading entire file at a time to make UI more responsive. Each chunk of file data is stored in double[] ,so many such arrays will be created in this whole process. 

I have attached an image below,  which shows UI display with top part PAN area where user can move mouse which causes file rendering frequently . For ex : if user move mouse 100 points, then 100 times file will be read & renders in graph. so it causes multiple  creation of double array. SO it forces garbage collection frequently and in turn it hit performance .

So , my question is whats the best architecture to fix  this problem so as to get best performance.

Is it good idea to create a pool of double array & reuse it, instead of creating double array every time for each chunk of file, so that we avoid frequent garbage collection.

For your inof, this application is more performance centric one, so request you to let me know the best architecture pattern to adapt.

Thanks in advance

Wpf problem with get SelectedItem

$
0
0

I have model

 public partial class RecipeIngr:ViewModelBase
    {
        private int? _count;

        [Key]
        [Column(Order = 0)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int IngrId { get; set; }

        [Key]
        [Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int RecipeId { get; set; }

        public int? Count
        {
            get { return _count; }
            set
            {
                _count = value;
                RaisePropertyChanged();
            }
        }

        public double Total
        {
            get { return (double) ((Ingredient.Price*Count)/100); }
        }

        public virtual Ingredient Ingredient { get; set; }
        public virtual Recipe Recipe { get; set; }
    }

 public partial class Recipe:ViewModelBase
    {
        private string _name;
        private string _description;

        [SuppressMessage("Microsoft.Usage","CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Recipe()
        {
            RecipeIngr = new List<RecipeIngr>();
        }

        public int RecipeId { get; set; }

        [Required]
        [StringLength(50)]
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                RaisePropertyChanged();
            }
        }

        public string Description
        {
            get { return _description; }
            set
            {
                _description = value;
                RaisePropertyChanged();
            }
        }

        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<RecipeIngr> RecipeIngr { get; set; }
    }


 public partial class Ingredient:ViewModelBase
    {
        private string _name;
        private double? _price;

        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Ingredient()
        {
            RecipeIngr = new List<RecipeIngr>();
        }

        [Key]
        public int IngtId { get; set; }

        [StringLength(50)]
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                RaisePropertyChanged();
            }
        }

        public double? Price
        {
            get { return _price; }
            set
            {
                _price = value;
                RaisePropertyChanged();
            }
        }

        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<RecipeIngr> RecipeIngr { get; set; }
    }

Then i Bind my Recipte to wpf window

<TabControl ItemsSource="{Binding Recipes}"><TabControl.ItemTemplate><DataTemplate><TextBlock Text="{Binding Name}"></TextBlock></DataTemplate></TabControl.ItemTemplate><TabControl.ContentTemplate><DataTemplate><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="*"></ColumnDefinition><ColumnDefinition Width="Auto"></ColumnDefinition></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="Auto"></RowDefinition><RowDefinition Height="Auto"></RowDefinition></Grid.RowDefinitions><DataGrid Grid.Row="0" Grid.Column="0" ItemsSource="{Binding RecipeIngr}" SelectedItem="{Binding SelectedIngredient}"  AutoGenerateColumns="False" IsReadOnly="True"><DataGrid.Columns><DataGridTextColumn Header="Ингредиент" Binding="{Binding Ingredient.Name}"></DataGridTextColumn><DataGridTextColumn Header="Кол-во (гр)" Binding="{Binding Count}"></DataGridTextColumn><DataGridTextColumn Header="Цена за 100 гр" Binding="{Binding Ingredient.Price}"></DataGridTextColumn><DataGridTextColumn Header="Итого" Binding="{Binding Total}"></DataGridTextColumn></DataGrid.Columns></DataGrid></Grid></DataTemplate></TabControl.ContentTemplate></TabControl>

And i want getselected item i create property (Type RecipeIngr) and bind to SelectedItem(DataGrid) but i get null((( where is wrong?


Internet Explore won't close on Exit of my WP app

$
0
0

Dear all,

My WPF app need to open a browser before starting in the folowing way :

IexplorerProcess = new System.Diagnostics.Process();
                        IexplorerProcess.StartInfo.FileName = "C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe";
                        IexplorerProcess.StartInfo.UseShellExecute = true;
                        IexplorerProcess.StartInfo.Arguments = "http://localhost/reports/";
                        IexplorerProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Minimized;

                        IexplorerProcess.Start();

When my application get started, then it open IE to the follwoing URL and gets mimimized. SO far so good

Then my goal is that when my application EXITS, I need to close the iE process. For that I am proceding as below :

IexplorerProcess.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
                IexplorerProcess.Kill();

The Kill method, never kill IE which is still in Task bar.

Any idea how to close IE process all time ?

regards

Displaying view inside another view

$
0
0

Hey everyone, I am quite new to WPF so please be patient if I dont possess the complete understanding.

I have several views in my program. I want to display a view inside another view. How can I do this? wht i have tried is:

    <Grid x:Name="LayoutRoot" Background="#FFA3A3A3">
        <Frame Source="XYGraphRandomSampleView.xaml" Width="500" Height="500"/>
    </Grid>

but the problem is, the complete view displays the source view. How can I display the contents of the source view shrinked in a small region(lets say 500x500 size)?

Get Index of Selected TreeViewItem in WPF TreeView

$
0
0

Hi,does anyone have solution how to retrieve index of selected TreeViewItem in WPF treeView (treeView is binded to ViewModel).

Thanks in advance.

Kind regards,

Almir

Wpf problem with get SelectedItem

$
0
0

I have model

 public partial class RecipeIngr:ViewModelBase
    {
        private int? _count;

        [Key]
        [Column(Order = 0)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int IngrId { get; set; }

        [Key]
        [Column(Order = 1)]
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int RecipeId { get; set; }

        public int? Count
        {
            get { return _count; }
            set
            {
                _count = value;
                RaisePropertyChanged();
            }
        }

        public double Total
        {
            get { return (double) ((Ingredient.Price*Count)/100); }
        }

        public virtual Ingredient Ingredient { get; set; }
        public virtual Recipe Recipe { get; set; }
    }

 public partial class Recipe:ViewModelBase
    {
        private string _name;
        private string _description;

        [SuppressMessage("Microsoft.Usage","CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Recipe()
        {
            RecipeIngr = new List<RecipeIngr>();
        }

        public int RecipeId { get; set; }

        [Required]
        [StringLength(50)]
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                RaisePropertyChanged();
            }
        }

        public string Description
        {
            get { return _description; }
            set
            {
                _description = value;
                RaisePropertyChanged();
            }
        }

        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<RecipeIngr> RecipeIngr { get; set; }
    }


 public partial class Ingredient:ViewModelBase
    {
        private string _name;
        private double? _price;

        [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Ingredient()
        {
            RecipeIngr = new List<RecipeIngr>();
        }

        [Key]
        public int IngtId { get; set; }

        [StringLength(50)]
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                RaisePropertyChanged();
            }
        }

        public double? Price
        {
            get { return _price; }
            set
            {
                _price = value;
                RaisePropertyChanged();
            }
        }

        [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<RecipeIngr> RecipeIngr { get; set; }
    }

Then i Bind my Recipte to wpf window

<TabControl ItemsSource="{Binding Recipes}"><TabControl.ItemTemplate><DataTemplate><TextBlock Text="{Binding Name}"></TextBlock></DataTemplate></TabControl.ItemTemplate><TabControl.ContentTemplate><DataTemplate><Grid><Grid.ColumnDefinitions><ColumnDefinition Width="*"></ColumnDefinition><ColumnDefinition Width="Auto"></ColumnDefinition></Grid.ColumnDefinitions><Grid.RowDefinitions><RowDefinition Height="Auto"></RowDefinition><RowDefinition Height="Auto"></RowDefinition></Grid.RowDefinitions><DataGrid Grid.Row="0" Grid.Column="0" ItemsSource="{Binding RecipeIngr}" SelectedItem="{Binding SelectedIngredient}"  AutoGenerateColumns="False" IsReadOnly="True"><DataGrid.Columns><DataGridTextColumn Header="Ингредиент" Binding="{Binding Ingredient.Name}"></DataGridTextColumn><DataGridTextColumn Header="Кол-во (гр)" Binding="{Binding Count}"></DataGridTextColumn><DataGridTextColumn Header="Цена за 100 гр" Binding="{Binding Ingredient.Price}"></DataGridTextColumn><DataGridTextColumn Header="Итого" Binding="{Binding Total}"></DataGridTextColumn></DataGrid.Columns></DataGrid></Grid></DataTemplate></TabControl.ContentTemplate></TabControl>

And i want getselected item i create property (Type RecipeIngr) and bind to SelectedItem(DataGrid) but i get null((( where is wrong?

Only manually check validation of wpf controls

$
0
0

Hi all,

I find a good sample(http://blog.scottlogic.com/2009/01/26/bindinggroups-for-total-view-validation.html) to explain how to use bindinggroup and manually invoke"BindingGroup.CommitEdit()" to manually check all controls' validation. but still has one issue that does not meet my requirement:

    When the window initialized and loaded, it seems controls whiched binding incorrected property value will display errortemplate although manually "BindingGroup.CommitEdit()" does not be invoked in code, for example, Person2.FirstName... Is it possible that all controls display normal even binding incorrect property value after window loading, and only display errortemplate after manually invoke "BindingGroup.CommitEdit()" ?

Thanks in advance,

Vince


everything is possible

System.Windows.Media.Fonts.SystemFontFamilies has different behavior in for >net frame work 3.5 and above

$
0
0

in .Net Frame work-3.5, System.Windows.Media.Fonts.SystemFontFamilies fetches those fonts which are present in thewindows font directory and also those which are activated through win32 APIAddFontResource and have a valid registry entry. 

But For .Net FrameWork > 3.5, it fetches only those fonts which are present in the windows default font directory. 

Question :-

-Is there any reason for this?

-How we can get the same behavior with .net frame work- 4 similar to.net frame work - 3.5 for System.Windows.Media.Fonts.SystemFontFamilies

generate treeviewItem

$
0
0

Hello,

i want this

+TextBox

  TextBox

  Textbox

I have the solution for the first part

+TextBox

  TextBox

But in want push the Enterkey and ia have this

+TextBox

  TextBox

  Textbox

Here the xml

<TreeView Name="trvMenu" TreeViewItem.Expanded="TreeViewItem_Expanded"   Height="200" HorizontalAlignment="Left" Margin="12,48,0,0"  VerticalAlignment="Top" Width="120" ItemsSource="{Binding}"><TreeView.Resources><Style TargetType="TreeViewItem"><EventSetter Event="KeyUp"
                             Handler="treeViewItem_KeyUp" /></Style></TreeView.Resources><TreeView.ItemTemplate><HierarchicalDataTemplate DataType="{x:Type TreeView}" ItemsSource="{Binding Items}"><TextBox></TextBox></HierarchicalDataTemplate></TreeView.ItemTemplate></TreeView>

and the C#:

    public void TreeViewItem_Expanded(object sender, RoutedEventArgs e)
        {
            TreeViewItem childItem1 = new TreeViewItem();
            TextBox txt = new TextBox();
            childItem1.Items.Add(txt);

private void treeViewItem_KeyUp(object sender, KeyEventArgs e)
        {

            if (e.Key == Key.Enter)
            {
                Handler(sender, e);
                Debug.WriteLine(" Enter");
 		TextBox txt = new TextBox();
                  item.Items.Add(txt); //thats is a error!
}
I want not a new treeviewitem i want in the treeviewitem only a new texbtbox


Names not supported under ResourceDictionary scope

$
0
0

Hi Everyone,

I have created a custom UI control in WPF platform. Within the generic file i have used the following code snippet

<ResourceDictionary

     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:local="clr-namespace:WpfCustomControlLibrary1">

    <ContextMenu x:Key="ContextMenuStyle">

        <MenuItem x:Name="Cut" Header="Cut">

        </MenuItem>

    </ContextMenu>

    <Style TargetType="{x:Type local:CustomControl1}">

        <Setter Property="ContextMenu" Value="{StaticResource ContextMenuStyle}"/>

        <Setter Property="Template">

            <Setter.Value>

                <ControlTemplate TargetType="{x:Type local:CustomControl1}">

                    <Border Background="{TemplateBinding Background}"

                            BorderBrush="{TemplateBinding BorderBrush}"

                            BorderThickness="{TemplateBinding BorderThickness}">

                        <Button x:Name="button">

                        </Button>

                    </Border>

                </ControlTemplate>

            </Setter.Value>

        </Setter>

    </Style>

</ResourceDictionary>

When i am running this code snippet in 3.5 framework i am getting System.Windows.Markup.XamlParseException Additional information: 'Cut' value cannot be assigned to property 'Name' of object 'System.Windows.Controls.MenuItem'. Names not supported under ResourceDictionary scope. But i am not getting any exception while running in other framework. Is there any solution to resolve this problem? 

How to make e.HorizontalChange to work in mvvm?

$
0
0

I got a thumb on a canvas, which was originally in the partial class but now I am changing it to MVVM. However, in doing so, I don't know how to tackle e.HorizontalChange from the code behind in MVVM, in the ViewModel. 

Thumb:

<Thumb x:Name="mythumb" Canvas.Left="{Binding mythumbLeft}" Canvas.Top="{Binding mythumbTop}" Background="Blue" Width="20"
                                                       Height="20" Panel.ZIndex="200"><i:Interaction.Triggers><i:EventTrigger EventName="DragDelta"><light:EventToCommand Command="{Binding onDragDeltaCmd}" /></i:EventTrigger><i:EventTrigger EventName="DragStarted"><light:EventToCommand Command="{Binding onDragStartedCmd}" /></i:EventTrigger><i:EventTrigger EventName="DragCompleted"><light:EventToCommand Command="{Binding onDragCompletedCmd}" /></i:EventTrigger></i:Interaction.Triggers></Thumb>

ViewModel:

            private void onDragDelta()
            {
                double yadjust = NozzleCanvasNHeight + e.VerticalChange;
                double xadjust = NozzleCanvasNWidth + e.VerticalChange;
                if ((xadjust >= 0 && (yadjust >= 0)))
                {
                    NozzleCanvasNWidth = xadjust;
                    NozzleCanvasNHeight = yadjust;
                   mythumbLeft = mythumbLeft +
                        e.HorizontalChange);
                mythumbTop = mythumbTop +
                        e.VerticalChange);
                }

            }

Originally e was System.Windows.Controls.Primitives.DragCompletedEventArgs e.

Make a Canvas fill it's parent container?

$
0
0
I am trying to make a Canvas fill the Grid cell, or StackPanel, or DockPanel that it is in. I have tried all 3 as the containiner for the StackPanel, but the height will not propertly adjust to fill it.

It is automatically stretching horizontally when I resize the window, but the vertical height of the Canvas will not fill up the rest of the containing objet. In fact, the  only way I can get any vertical height at all it to specify the height in the XAML, which kills all hope of resizing.


I have also tried the Height="{Binding Path=ActualHeight, ElementName=container}" trick, but it seems to send it to an infinity, unless the container that is referenced also has a hard-coded height.

<Canvas Name="canvas1" Background="#7920619E"Margin="0,0,0,5" Height="{Binding Path=ActualHeight, ElementName=container}" DockPanel.Dock="Top" />

Add Control to a Column in a Grid in Code

$
0
0

How should i go about adding a control to a column in a grid, in code?

i tried doing:

(the following in entered in a sub)

 Dim newControl As New Control
 Dim PictureGrid As New Grid
 Dim newcol As New ColumnDefinition With {.Width = New GridLength(68)}
 PictureGrid.ColumnDefinitions.Add(newcol)
 PictureGrid.SetColumn(newControl, 0)
 PictureGrid.Children.Add(newControl)
 MainGrid.Children.Add(PictureGrid)

but this gave me an warning:

PictureGrid.SetColumn

the warning says:

Thanks,

Tamir.


~Tamir


TextBlock Inline Binding using DependencyProperty

$
0
0

I'm using MVVM Light. this is what I have:

in my view model:

        public ObservableCollection<Inline> InlineList
        {
            get { return _inlineList; }
            set { Set(() => InlineList, ref _inlineList, value); }
        }

public void SendButtonClicked()

{

 InlineList.Add(new Run("This is some bold text"));

}

public class BindableTextBlock : TextBlock
    {

        public ObservableCollection<Inline> InlineList
        {
            get { return (ObservableCollection<Inline>) GetValue(InlineListProperty); }
            set { SetValue(InlineListProperty, value); }
        }

        public static readonly DependencyProperty InlineListProperty =
            DependencyProperty.Register("InlineList", typeof(ObservableCollection<Inline>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged));


        //FrameworkPropertyMetadata

        public static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue == null) return;

            var textBlock = (BindableTextBlock)sender;
            textBlock.Inlines.AddRange((ObservableCollection<Inline>)e.NewValue);
        }
    }       

xaml:

<testRobot:BindableTextBlock Grid.Row="8" 
                                     Width="100" Height="100"
                                     Background="White"
                                     InlineList="{Binding InlineList}">
        </testRobot:BindableTextBlock>

The problem is that bound property InlineList never gets updated when the method SendButtonClicked gets pressed. I don't see any text I add to the collection ObservableCollection. When I put a break point in OnPropertyChanged method it never gets hit. I know my data context is set correctly as other bound controls work. What could be the problem?

Viewing all 18858 articles
Browse latest View live