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

User Control with combobox

$
0
0

I created a UserControl with TextBlock, TextBox and ComboBox

I have MainWindow with TabControl and this tabcontrol has several UserControls, one UserControl per TabItem

The UserControls in TabItems have the custom UserContol that I created.

Everything is working fine except the ComboBox, the ComboBox fills with data items and SelectedValue, but when I switch tabs on the MainWindow the Property that's bond to the SelectedValue gets set to null value and I can not figure out what is passing the null value, I put a break point inside the ComboBox SelectedValue setter property and the value shows null when the program hits the break point, but when I try to continue stepping through the code the code exits the Set portion of the property and goes to the Get portion, it does that twice and then goes to the next Object so I can't figure out what is passing the null value.  The SelectedValue gets correct value when I open the program, but gets nulls when I switch tabs.

I am new to WPF so I am not sure what I am doing.

I know it's probably impossible to tell what is causing this without seeing the entire program, but maybe someone had similar issue and has an advice on how to trouble shoot this or at least some suggestion on how to create an UserControl.

Here's the XAML to my custom UserControl


<UserControl x:Class="Vtsr.Views.CustomControls.VisitDataField"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:customControls="clr-namespace:Vtsr.Views.CustomControls"
             mc:Ignorable="d"
             x:Name="VisitDataFieldControl"
             d:DesignHeight="21" d:DesignWidth="300">

    <UserControl.Resources>
        <Style TargetType="ComboBox" x:Key="ComboBoxStyle">
            <Setter Property="Height" Value="20"></Setter>
            <Setter Property="FontSize" Value="{Binding FontSize}"></Setter>
        </Style>

        <Style TargetType="ComboBoxItem" x:Key="ComboBoxItemStyle">
            <Setter Property="BorderBrush" Value="Gray"></Setter>
            <Setter Property="BorderThickness" Value="0.0"></Setter>
        </Style>

        <Style x:Key="TextBlockStyle" TargetType="TextBlock">
            <Setter Property="FontSize" Value="{Binding FontSize}"></Setter>
            <Setter Property="FontWeight" Value="Bold"></Setter>
            <Setter Property="Margin" Value="3"></Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="TextDecorations" Value="Underline" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </UserControl.Resources>

    <Grid DataContext="{Binding ElementName=VisitDataFieldControl}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="100"></ColumnDefinition>
        </Grid.ColumnDefinitions>

        <TextBlock x:Uid="TxbLabel" x:Name="DataLabel" Margin="1,1,5,1" VerticalAlignment="Center" Width="{Binding LabelWidth}"
                           Text="{Binding DataLabelValue}" MinWidth="20" Grid.Row="0" Grid.Column="0" Style="{StaticResource TextBlockStyle}"></TextBlock>

        <customControls:FieldTextBox Text="{Binding DataField}" Grid.Row="0" Grid.Column="1" Margin="1,1,5,1" MouseRightButtonDown="TextBox_MouseRightButtonDown"></customControls:FieldTextBox>
        <ComboBox ItemsSource="{Binding UnitsList}" Grid.Row="0" Grid.Column="2" Style="{StaticResource ComboBoxStyle}" 
                                        ItemContainerStyle="{StaticResource ComboBoxItemStyle}" SelectedValue="{Binding SelectedUnit, Mode=TwoWay}">

        </ComboBox>
    </Grid>
</UserControl>

Here's code for the custom UserControl

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using Vtsr.Model;

namespace Vtsr.Views.CustomControls
{
    /// <summary>
    /// Interaction logic for VisitDataField.xaml
    /// </summary>
    public partial class VisitDataField : INotifyPropertyChanged
    {
        public VisitDataField()
        {
            InitializeComponent();
        }

        public void Connect(int connectionId, object target)
        {
            throw new NotImplementedException();
        }

        public static readonly DependencyProperty LabelWidthProperty = DependencyProperty.Register("LabelWidth", typeof(int), typeof(VisitDataField), null);
        public int LabelWidth
        {
            get
            {
                return (int)GetValue(LabelWidthProperty);
            }
            set
            {
                SetValue(LabelWidthProperty, value);
            }
        }

        public static readonly DependencyProperty DataFieldProperty = DependencyProperty.Register("DataField", typeof(string), typeof(VisitDataField), null);
        public string DataField
        {
            get { return (string)GetValue(DataFieldProperty); }
            set { SetValue(DataFieldProperty, value); }
        }

        public static readonly DependencyProperty SelectedUnitProperty = DependencyProperty.Register("SelectedUnit", typeof(string), typeof(VisitDataField), null);
        public string SelectedUnit
        {
            get
            {
                return (string)GetValue(SelectedUnitProperty);
            }
            set
            {
                SetValue(SelectedUnitProperty, value);
            }
        }
        public string DataLabelValue
        {
            get
            {
                return _dataLabelValue;
            }
            set
            {
                _dataLabelValue = value;
                if (CaptionDictinaryViewModel.CaptionDictionary != null)
                _dataLabelValue = CaptionDictinaryViewModel.CaptionDictionary.ContainsKey(value) ? CaptionDictinaryViewModel.CaptionDictionary[value] : value;

                OnPropertyChanged("DataLabelValue");
            }
        }

        private string _dataLabelValue = "Data Label";

        public static readonly DependencyProperty UnitsListProperty = DependencyProperty.Register("UnitsList", typeof(ObservableCollection<string>), typeof(VisitDataField), null);

        public ObservableCollection<string> UnitsList
        {
            get { return (ObservableCollection<string>) GetValue(UnitsListProperty); }
            set { SetValue(UnitsListProperty, value);}
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string name)
        {
            var handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(name));
            }
        }

        private void TextBox_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {

        }
    }
}


Peter


XBAP Parts of Siziable Window Dissappears When Moved

$
0
0
I attempting my first WPF application.  Its a browser app, XBAP,  that is being converted from a javascript/Activex browser based app.  With some trail and error and lot of great info on the w3 I have almost completed it.  I was testing when select a resizable window and dragged it with the mouse.  I saw parts of the User Interface disappear.  When I move the browser window random parts go blank and if I move it enough the whole app area is blank.  Maximizing the browser or alt-tab to another window and back restores the User Interface.  What could be causing this?

Kenney

WPF TreeView with large ItemSource

$
0
0

Hi All,

We are binding 18000 childitem to a Node and we open the window which has the treeview.

Detailed Flow:

Ww have Node called "Customer" which has 18000 child node. These child nodes are kept in an Observable Collection.

The caption of this parentNode "Customer" is bound to a SplitButton.

When we click the SplitButton, a window is intialized with this parentNode.

ParentNode caption is displayed as heading for the window, and childNodes of the "Customer" parent Node is displayed in the window.

we named the window as memberEditor, 

memberEditor.ShowDialog(); takes long time to load. After 5 Minutes only loaded event of window(member editor) is triggered.

Window has been loaded, but the UI is locked permanently. 

Is there any way to make the data loaded in on demand, such as when scroll down or clicking a button(next 500 Nodes) data will be loaded to TreeView?

Please advice me to get rid out of this problem.

Thanks,

JasSelvaParvathi

How to notify Parent Observable Collection when child observable collection property value changes in MVVM?

$
0
0

 Hi EveryOne,

               I need to notify Parent Observable Collection when child observable collection property value get changed. In my scenario, I need to update Parent Observable collection residing in ViewModel and it didn't get notified when child observable collection property value changed even i used INotifyPropertyChanged. Can any one help me to solve this problem with a piece of code.

 

Thanks,

StalinRaj.

how to access a file using FileReader in XBAP?

$
0
0

Hi Everyone,

                I am working in XBAP application. Now XBAP running as Full Trust application. When ever an error occurs that error is logged in a seperate file in the running application itself. XBAP won't allow me to open and append the file (Log Messages) and it throws exception as UnAuthorized Exception. Can any one help me to solve this problem to access File?.(Here, iam using TextWriter class and open file using File.Append)

Thanks,

StalinRaj.


WPF Element Control with Buttons Hosted in a Windows Form

$
0
0

I created a UserControll in WPF to be hosted into my Windows Form Application. Inside my usercontrol are 7 buttons and a textbox I plan on using to search a database. How do you access the Buttons inside the Usercontrol that is hosted inside the Element Host? I currently have the usercontrol hosted in the Element Host in my windows form.

I need to be able to get to the Click Events for each button so I can program each button to connect to the Sql database to present the data into the DataGridView. As of right now I have buttons programmed from the Windows Form application that works great, but I want to add more style to my application. Only WPF allows you to fully design the components the way you want them.

Currently using Visual Studio Professional 2013 / .Net 4.5.1

Exception of type 'System.OutOfMemoryException' was throw

$
0
0

Hi,
 
Can any one please help me its urgent.
 
I am having one lakh record in my datatable while compress and de compress and after serialize i am getting Exception of type 'System.OutOfMemoryException' was throw.

If i am working with 20000 datas its working.i increase max length in web config that also not working

I AM USING WCF+WPF
 
My Code is
 

public static MemoryStream DataTableSerialization(DataTable dtSearchDataTable) 
{ 
System.IO.MemoryStreamstream = newSystem.IO.MemoryStream(); 
System.Runtime.Serialization.IFormatterformatter = newSystem.Runtime.Serialization.Formatters.Binary.BinaryFormatter();  

byte[] bytes = null;     
MemoryStreammemory = newMemoryStream();  
try
{ dtSearchDataTable.RemotingFormat = SerializationFormat.Binary;                

formatter.Serialize(stream, dtSearchDataTable);//Here i am getting error 
bytes = stream.ToArray();
using(vargzip = newGZipStream(memory, CompressionMode.Compress, true))
                 {                     gzip.Write(bytes, 0, bytes.Length);                 }                 memory.Position = 0;

// ---  In order to enable reading option during Deserialzation on client side we need to set Position = 0             }        


catch(Exceptionex)
             {    }

finally
            {                 stream.Dispose();                 MinimizeMemory();             }           


returnmemory;
         }


 
My Webconfig(WCF)
      

<openTimeout="04:01:00"receiveTimeout="04:10:00"sendTimeout="04:01:00"   

bypassProxyOnLocal="false"hostNameComparisonMode="StrongWildcard"          

maxBufferSize="2147483647"maxBufferPoolSize="2147483647"maxReceivedMessageSize="2147483647"   

messageEncoding="Text"textEncoding="utf-8"useDefaultWebProxy="true"     

allowCookies="false"><readerQuotasmaxDepth="32"maxStringContentLength="2147483647"maxArrayLength="2147483647" 
maxBytesPerRead="4096"maxNameTableCharCount="16384"/>                 bindingname="SearchBinding"closeTimeout="04:01:00">




WPF MVVM ContextMenu binding IsOpen to view model

$
0
0
I have a button with a context menu associated to it.  I can right click on the button and show the context menu as you would expect, however I want to be able to show the context menu after another event, such as a left click, or a drag and drop style event.

I am attempting to do this by binding the IsOpen property of the context menu to the view model, but this is not working as expected.  On first left click of the button, nothing happens, although I can see the property on the view model that IsOpen is bound to being updated correctly.

If I right click, the menu will display correctly, and after this if I left click the menu will also show.

Has anyone ever seen this or have any ideas on what I need to do to get the contextMenu to open when the IsOpen property is updated?


XAML

    
<Window x:Class="PopUpTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mvp="clr-namespace:PopUpTest"
        Title="MainWindow" Height="350" Width="525" x:Name="This"><Window.DataContext><mvp:MainWindowViewModel /></Window.DataContext><Grid><Grid.Resources><ContextMenu x:Key="Menu" DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}" IsOpen="{Binding PopupViewModel.IsOpen, Mode=TwoWay}"><MenuItem Header="Delete" /></ContextMenu></Grid.Resources><Button Command="{Binding DisplayPopupCommand}" ContextMenu="{StaticResource Menu}" Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type Grid}}}"/></Grid></Window>



Code Behind

    
using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using Microsoft.Practices.Prism.Commands;

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

    public class MainWindowViewModel : BaseViewModel
    {
        private readonly PopupViewModel<ChildViewModel> _popupViewModel;
        private readonly DelegateCommand _displayPopupCommand;

        public MainWindowViewModel()
        {
            _popupViewModel = new PopupViewModel<ChildViewModel>(new ChildViewModel { FirstName = "John", LastName = "Doe" });
            _displayPopupCommand = new DelegateCommand(() => { PopupViewModel.IsOpen = PopupViewModel.IsOpen == false; Console.WriteLine(PopupViewModel.IsOpen); });
        }

        public ICommand DisplayPopupCommand
        {
            get { return _displayPopupCommand; }
        }

        public PopupViewModel<ChildViewModel> PopupViewModel
        {
            get { return _popupViewModel; }
        }
    }

    public class PopupViewModel<T> : BaseViewModel
    {
        private readonly T _data;

        public PopupViewModel(T data)
        {
            _data = data;
        }

        public T Data
        {
            get { return _data; }
        }

        private bool _isOpen;
        public bool IsOpen
        {
            get { return _isOpen; }
            set
            {
                if (_isOpen != value)
                {
                    _isOpen = value;
                    OnPropertyChanged("IsOpen");
                }
            }
        }
    }

    public class ChildViewModel : BaseViewModel
    {
        private string _firstName;
        public string FirstName
        {
            get { return _firstName; }
            set
            {
                if (_firstName != value)
                {
                    _firstName = value;
                    OnPropertyChanged("FirstName");
                }
            }
        }

        private string _lastName;
        public string LastName
        {
            get { return _lastName; }
            set
            {
                if (_lastName != value)
                {
                    _lastName = value;
                    OnPropertyChanged("LastName");
                }
            }
        }

    }

    public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

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

Thanks


How to set dependency property of type List

$
0
0

Hi,

I have a dependency property FilterMemberPath of type List<string> exposed from a user control.

Now I when I use the user control say FilterControl in my application like this:

<uc:FilterControl>
<uc:FilterControl.Style>
                        <Style TargetType="wpfCustomControls:FilterComboBox">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Path=SomeParam}" Value="Name">
                                    <Setter Property="FilterMemberPath">
                                        <Setter.Value>
                                            <sys:String>Name</sys:String>
                                            <sys:String>Code</sys:String>
                                        </Setter.Value>
                                    </Setter>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </uc:FilterControl.Style>
</uc:FilterControl>

It does not allow me to Set values in setter.Please help me with this as how can we set values for List<string> type dependecy property.

Biding MenuItem Commands to Specific Pages

$
0
0

Hello,

I am working in a WPF application that contains a Frame with serveral Pages in it. The Frame object is in a Windows where there is also a Menu with several MenuItems.

I would like to know what would be a good way to respond to MenuItem clicks inside a specific page, since they do not hold a reference to the menu object.

I was thinking about using Command Binding, but not sure how this could be done..

Any toughts?

Igor.


.NET Software developer for industrial internet and automation system.

how to set Dockpanel in WPF Usercontrol ?

$
0
0

Hi,

I have a WPF usercontrol which wants design like a property window in visual studio below is my code and screenshots . please guide me..

  <ScrollViewer>        <Grid>            <Grid.RowDefinitions>                <RowDefinition Height="20"></RowDefinition>                <RowDefinition Height="5"></RowDefinition>                <RowDefinition Height="Auto"></RowDefinition>                <RowDefinition Height="20"></RowDefinition>                <RowDefinition Height="Auto"></RowDefinition>            </Grid.RowDefinitions>            <StackPanel Orientation="Horizontal" Grid.Row="0">                <Grid>                    <Grid.RowDefinitions>                        <RowDefinition Height="20"></RowDefinition>                    </Grid.RowDefinitions>                    <Grid.ColumnDefinitions>                        <ColumnDefinition Width="5"></ColumnDefinition>                        <ColumnDefinition Width="20"></ColumnDefinition>                        <ColumnDefinition Width="5"></ColumnDefinition>                        <ColumnDefinition Width="20"></ColumnDefinition>                    </Grid.ColumnDefinitions>                    <Button Grid.Row="0" Grid.Column="1" Name="btnConnectSqlLiteDatabase" ToolTip="Add Sqlite Connection" Click="btnConnectSqlLiteDatabase_Click" Style="{StaticResource TransaparentButton}">                        <Image Height="20" Width="20" Source="./Images/AddSqliteConnection.png"></Image>                    </Button>                    <!--<Button Grid.Row="0" Grid.Column="3" Name="btnDisConnectSqlLiteDatabase" ToolTip="Add Sqlite Connection" Click="btnDisConnectSqlLiteDatabase_Click" Style="{StaticResource TransaparentButton}">                    <Image Height="20" Width="20" Source="./Images/RemoveSqliteconnection.jpg"></Image>                </Button>-->                </Grid>            </StackPanel>            <!--<StackPanel Orientation="Horizontal" Grid.Row="2">-->            <DockPanel Grid.Row="2" VerticalAlignment="Top" HorizontalAlignment="Stretch">                <TreeView Name="tvWorkflowConfiguration" Background="Transparent" BorderBrush="Transparent" Width="Auto" Height="Auto" HorizontalAlignment="Stretch">                    <TreeView.ItemContainerStyle>                        <Style TargetType="{x:Type TreeViewItem}">                            <EventSetter Handler="tvWorkflowConfiguration_MouseRightButtonDown" Event="TreeViewItem.MouseRightButtonDown">                            </EventSetter>                            <EventSetter Handler="TreeViewItem_Selected" Event="Selected"></EventSetter>                            <Setter Property="IsExpanded" Value="True"></Setter>                        </Style>                    </TreeView.ItemContainerStyle>                    <TreeView.Resources>                        <HierarchicalDataTemplate DataType="{x:Type loc:WorkFlows}" ItemsSource="{Binding Path=WorkFlowConfigCollection}">                            <StackPanel Orientation="Horizontal">                                <StackPanel.ContextMenu>                                    <ContextMenu>                                        <MenuItem Header="AddWorkFlow"  Command="{Binding Path=RunNewWorkFlowCommand}" CommandParameter="{Binding}"></MenuItem>                                    </ContextMenu>                                </StackPanel.ContextMenu>                                <Image Source=".\Images\Root.png" Width="20" Height="20" />                                <TextBlock Text="{Binding Path=Name}" />                                <StackPanel.Effect>                                    <DropShadowEffect BlurRadius="2" Color="LightGray" Opacity=".2"></DropShadowEffect>                                </StackPanel.Effect>                            </StackPanel>                        </HierarchicalDataTemplate>                        <HierarchicalDataTemplate DataType="{x:Type loc:WorkFlow}" ItemsSource="{Binding Path=WorkItems}">                            <StackPanel Orientation="Horizontal">                                <StackPanel.ContextMenu>                                    <ContextMenu>                                        <MenuItem Header="{Binding Path=EditWorkFlow}"  Command="{Binding Path=RunEditWorkFlowCommand}" CommandParameter="{Binding}"></MenuItem>                                        <MenuItem Header="{Binding Path=AddWorkItem}"  Command="{Binding Path=RunNewWorkItemCommand}" CommandParameter="{Binding}"></MenuItem>                                        <MenuItem Header="{Binding Path=Remove}"  Command="{Binding Path=RunRemoveWorkFlowCommand}" CommandParameter="{Binding}"></MenuItem>                                    </ContextMenu>                                </StackPanel.ContextMenu>                                <Image Source=".\Images\workflow_icon.jpg" Width="20" Height="20"></Image>                                <TextBlock Text="{Binding Path=Name}" Padding="3">                                </TextBlock>                                <StackPanel.Effect>                                    <DropShadowEffect BlurRadius="2" Color="LightGray" Opacity=".2"></DropShadowEffect>                                </StackPanel.Effect>                            </StackPanel>                        </HierarchicalDataTemplate>                        <HierarchicalDataTemplate DataType="{x:Type loc:WorkItem}">                            <StackPanel Orientation="Horizontal">                                <StackPanel.ContextMenu>                                    <ContextMenu>                                        <MenuItem Header="{Binding Path=EditWorkItem}" Command="{Binding Path=RunEditWorkItemCommand}" CommandParameter="{Binding}"></MenuItem>                                        <MenuItem Header="{Binding Path=Remove}"  Command="{Binding Path=RunRemoveWorkItemCommand}" CommandParameter="{Binding}"></MenuItem>                                    </ContextMenu>                                </StackPanel.ContextMenu>                                <Image Source=".\Images\workitem_icon.jpg" Width="20" Height="20"></Image>                                <TextBlock Text="{Binding Path=Name}" Padding="3"></TextBlock>                                <StackPanel.Effect>                                    <DropShadowEffect BlurRadius="2" Color="LightGray" Opacity=".2"></DropShadowEffect>                                </StackPanel.Effect>                            </StackPanel>                        </HierarchicalDataTemplate>                    </TreeView.Resources>                </TreeView>            </DockPanel>            <!--</StackPanel>-->            <StackPanel Orientation="Horizontal" Grid.Row="3" VerticalAlignment="Bottom">            </StackPanel>            <DockPanel Grid.Row="4" VerticalAlignment="Bottom" HorizontalAlignment="Stretch">                <!--<StackPanel Orientation="Horizontal" Grid.Row="4" VerticalAlignment="Bottom" HorizontalAlignment="Stretch">-->                <Grid Width="Auto">                    <Grid.RowDefinitions>                        <RowDefinition Height="20"></RowDefinition>                        <RowDefinition Height="*"></RowDefinition>                    </Grid.RowDefinitions>                    <TextBlock Text="Properties" Grid.Row="0" ></TextBlock>                    <DataGrid x:Name="dgPropertyViewer"                              AutoGenerateColumns="False"                              ItemsSource="{Binding}"                               Grid.Row="1"                              CanUserSortColumns="False"                               ColumnWidth="SizeToCells"                               HorizontalAlignment="Stretch" >                        <DataGrid.Columns>                            <DataGridTextColumn Binding="{Binding Key}" Header="Name" IsReadOnly="True" Width="*" />                            <DataGridTextColumn Binding="{Binding Value}" Header="Value" IsReadOnly="True" Width="*" />                        </DataGrid.Columns>                    </DataGrid>                </Grid>                <!--</StackPanel>-->            </DockPanel>        </Grid>    </ScrollViewer>


second image property datagrid should reside same as visual studio property window ForeColor box and Top Treeview should reside same as visual studio property window Top values with Scroll bar.

Data binding does not work in XPS

$
0
0

Hi,

I'm generating XPS reports in a non-WPF application. Sometimes, the bound data is not rendered in the report and I cannot understand why.The GUI is correctly rendered, but XPS is not. I have searched the net for days. It seems at least a few others are experiencing the same problem. Let's create a sample project that demonstrates the problem! Please note that I cannot print the Visual directly since the printing function may be used in a service or similar.

1) Create a WPF project called WpfApplication1.
2) Replace the MainWindow class with the code below.
3) Add a my_template.xaml file to the solution and change its Build Action to "None".
4) Add the my_template.xaml file (code below) to the application's resources (Resources.resx).
5) Add references to ReachFramework and System.Printing.
6) Run the application! The GUI shows the text "test", but the generated XPS document (saved on your Desktop) does not!

Note the trace window. This is the last trace after the dispatcher has updated the bindings:

System.Windows.Data Warning: 89 : BindingExpression (hash=8761922): TransferValue -using final value 'test'

What is going on?!

MainWindow.xaml.cs

public partial class MainWindow : Window
{
 public MainWindow()
 {
  InitializeComponent();

  DataContext = "test";
 }

 private void Window_Loaded(object sender, RoutedEventArgs e)
 {
  var documents = new List<FixedDocument>();

  var document = XamlReader.Parse(WpfApplication1.Properties.Resources.my_template) as FixedDocument;

  InjectData(document, DataContext);

  documents.Add(document);

  string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
  string filename = System.IO.Path.Combine(path, "XpsTest.xps");

  using (var stream = File.Create(filename))
  {
   ConvertToXps(documents, stream);
  }

  foreach (var fixedPage in document.Pages.Select(pageContent => pageContent.Child))
  {
   fixedPage.Children.Clear();
  }
 }

 protected void InjectData(FixedDocument document, object dataSource)
 {
  document.DataContext = new { MyTextData = dataSource };

  // we need to give the binding infrastructure a push as we
  // are operating outside of the intended use of WPF
  var dispatcher = Dispatcher.CurrentDispatcher;
  dispatcher.Invoke(
     DispatcherPriority.SystemIdle,
     new DispatcherOperationCallback(delegate { return null; }),
     null);
 }

 protected void ConvertToXps(IEnumerable<FixedDocument> fixedDocuments, Stream outputStream)
 {
  var package = Package.Open(outputStream, FileMode.Create);
  var xpsDoc = new XpsDocument(package, CompressionOption.Normal);
  var xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);

  // XPS documents are built using fixed document sequences.
  var fixedDocSeq = new FixedDocumentSequence();

  foreach (var fixedDocument in fixedDocuments)
  {
   var docRef = new DocumentReference();
   docRef.BeginInit();
   docRef.SetDocument(fixedDocument);
   docRef.EndInit();
   ((IAddChild)fixedDocSeq).AddChild(docRef);
  }

  // Write out our fixed document to XPS.
  xpsWriter.Write(fixedDocSeq.DocumentPaginator);

  xpsDoc.Close();
  package.Close();
 }
}

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Loaded="Window_Loaded"
        Title="MainWindow"
        Width="793.92" Height="1122.24" Margin="100"><Grid HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="200"><TextBlock Background="LightGray" Text="{Binding}"
                   FontSize="36"/></Grid></Window>

my_template.xaml

<FixedDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
               xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><PageContent><FixedPage Width="793.92" Height="1122.24" Margin="100"><Grid HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="200"><TextBlock Background="LightGray" Text="{Binding MyTextData,PresentationTraceSources.TraceLevel=High}"
                           FontSize="36"/></Grid></FixedPage></PageContent></FixedDocument>

Default Type Conversion in XAML

$
0
0

I'm trying to find any specifications or rules that define exactly what types are created when property values are specified in XAML as strings, consider:

<UserControl x:Class="TestControl.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"><StackPanel><StackPanel Background="CadetBlue" VerticalAlignment="Center"><TextBlock>Text</TextBlock><TextBlock>Text</TextBlock></StackPanel><StackPanel><DockPanel><TextBlock>Text</TextBlock><TextBlock>Text</TextBlock><Border></Border>    <Canvas><StackPanel><TextBlock>Text</TextBlock><TextBlock>Text</TextBlock></StackPanel></Canvas></DockPanel></StackPanel></StackPanel></UserControl>

As you can see the 'Background' property (a Brush, which is an abstract class) is set using the string 'CadetBlue'.

I want to know what concrete type (some derivative of Brush) the string is converted to and how that conversion is done.

If we were to create say a SolidColorBrush, we'd first have to create aColor from 'CadetBlue' and so on.

I'm trying to establish a general set of rules for any property that set in XAML like this, perhaps there's some default conversion class working behind the scenes that standard XAML uses, but any info about all this is appreciated.

Thanks

Cap'n


'ResourceDictionary' root element is a generic type and requires a x:Class attribute to support the x:TypeArguments attribute sp

$
0
0

 

Error : 'ResourceDictionary' root element is a generic type and requires a x:Class attribute to support the x:TypeArguments attribute specified on the root element tag.

 

Hi,

 

I get this error when i include some namespaces in my ResourceDictionary to specify a Style for a custom control.
Can anyone help me?

 

Thx

Stardusty

How to do treeview hierarchical data binding with lazy load ?

$
0
0
I'm learning WPF and encountered this issue. When building file folder browser using treeview from code I encountered major performance problem due to large number of folders in the C:\Windows directory. I'm using lazy load from code obviously but it does not help that much for this particular folder. I think part of the problem is that Windows 8 creates several thousands subfolders in one of the Windows sub directories. When opening 3000 or so folders the code creates 3000 TreeViewItems with associated icon graphics created 3000 times from XAML vector image. I want to keep it vector so the program will adjust properly when high DPI density screen is used. So then I googled for advice and found that it helps tremendously performance to use virtualization of the treeview items panel in conjunction with hierarchical binding. I managed to do hierarchical binding but I have no idea how do you fire up IsExpanded event on the data class from the associated through binding TreeViewItem such that the lazy load can work by opening sub directories from the node that is being expanded. Is there a way or binding does not provide such mechanism to transmit events from UI back to the data class ?

CompositePresentationEvent order of execution

$
0
0

If i publish multiple events in a single threaded environment, in what order will the subscribers be invoked?

for intance,

Event 1

UpdateCartEventArgs args = new UpdateCartEventArgs (param);
eventAggregator.GetEvent<UpdateCartEventArgs >().Publish(args);

Event 2

eventAggregator.GetEvent<RunTotalEvent>().Publish(
                     new RunTotalEventEventArgs(param));

In which order will the subscribers be called? Is it guarenteed (in a single threaded environment) that Event 1's subscriber will be invoked before event 2?


Anonymous

UI not updating when ItemsControl is bound to ObservableCollection containing a list of ViewModels

$
0
0

Development Environment: Visual Studio 2010, using .NET 4.0.

I have a UserControl which has a ItemsControl tag with ItemsSource bound to an ObservableCollection containing a list of view models.  The reason for this is because within the main UserControl contains another UserControl which the view model to the inner UserControl changes after a certain time period.  There are also two buttons on the left and right of the main UserControl which allows the user to change the view model of the inner UserControl manually.

XAML code for the main UserControl, called MetricStatusDisplayControl.xaml looks thusly:

<Grid x:Name="StatusItemGrid" Margin="10,0,10,4" Grid.Row="1" HorizontalAlignment="Center" Width="330"><Grid.Resources><Style TargetType="{x:Type local:EnvironmentalViewUserControl}"><Setter Property="Margin" Value="0,8,0,0"/></Style></Grid.Resources><ItemsControl x:Name="itemsControl" ItemsSource="{Binding DetailStatuses}"><ItemsControl.ItemTemplate><DataTemplate><local:EnvironmentalViewUserControl d:LayoutOverrides="Width, Height"/></DataTemplate></ItemsControl.ItemTemplate></ItemsControl></Grid><Button x:Name="LeftNavigateButton" Visibility="{Binding IsMoreThanOneModel}" Content="Button" HorizontalAlignment="Left" Width="30" Grid.Row="1" Template="{DynamicResource StatusNavLeftButtonControlTemplate}" Command="{Binding LeftNavigationButtonClickCommand}" VerticalAlignment="Center"/><Button x:Name="RightNavigateButton" Visibility="{Binding IsMoreThanOneModel}" Content="Button" Grid.Row="1" Template="{DynamicResource StatusNavRightButtonControlTemplate}" Command="{Binding RightNavigationButtonClickCommand}" HorizontalAlignment="Right" Width="30" VerticalAlignment="Center"/>

The LeftNavigateButton and RightNavigateButton are each bound to their respective ICommand property in the view model, which changes the DetailStatuses, an ObservableCollection containing a view model which gets changed to another view model if either of the navigate button gets pushed.   This aspect works fine.

The issue arose when I want the view model for the inner UserControl to rotate every few seconds on a timer.  Even though I've set DetailStatuses with the new inner view model and called OnPropertyChanged("DetailStatuses"); in the main view model, but the UI does not reflect the change.  For some reason it updates when the navigate buttons are pushed, but calling the same function from the timer does not update the UI.

The C# view model code for the main UserControl is here thusly:

   /// <summary>
   /// A UI-friendly wrapper for Environmental View object.
   /// </summary>
   public class EnvironmentalViewModel : StatusViewModelBase, IConfigurable, INotifyPropertyChanged
   {
      #region Private Fields

      /// <summary>
      /// The back end environmental model.
      /// </summary>
      private EnvironmentalModel environmentalModel;

      /// <summary>
      /// List of view models for each environmental item.
      /// </summary>
      private ObservableCollection<StatusViewModelBase> detailStatuses;

      /// <summary>
      /// Current Environmental item in view.
      /// </summary>
      private int currentViewIndex = 0;

      /// <summary>
      /// The configuration specs for the widget.
      /// </summary>
      private EnvironmentalConfiguration theConfiguration = new EnvironmentalConfiguration();

      /// <summary>
      /// List of environmental items to display in the widget.
      /// </summary>
      private readonly ObservableCollection<StatusViewModelBase> EnvironmentalItems = new ObservableCollection<StatusViewModelBase>();

      /// <summary>
      /// The timer for the time elapsed for each transmission info in the queue.
      /// </summary>
      private Timer _aTimer;

      /// <summary>
      /// The time that this widget was instantiated.
      /// </summary>
      private DateTime currentTime;

      /// <summary>
      /// For checking when timer is up to certain number of seconds.
      /// </summary>
      private TimeSpan duration;

      #endregion

      #region Constructor

      /// <summary>
      /// 
      /// </summary>
      /// <param name="configuration"></param>
      private EnvironmentalViewModel(EnvironmentalConfiguration configuration)
      {
         theConfiguration = configuration;

         environmentalModel = new EnvironmentalModel(theConfiguration);
         detailStatuses = new ObservableCollection<StatusViewModelBase>();
         foreach (EnvironmentalItem item in environmentalModel.EnvironmentalItems)
         {
            EnvironmentalItems.Add(new EnvironmentalDetailViewModel(environmentalModel, item));
         }

         // When first configured, show only the first element in the EnvironmentalItems list
         detailStatuses.Add(EnvironmentalItems[0]);

         // if there are more than 1 submodels, start flipping between the submodels
         if (environmentalModel.NumberOfSubModels > 1)
         {
            // set up the timer for flipping the submodels
            currentTime = DateTime.Now;
            _aTimer = new Timer();
            _aTimer.Interval = Constants.SECOND_TO_MILLISECONDS;
            _aTimer.Elapsed += OnCountUpEvent;
            _aTimer.Start();
         }
      }

      #endregion // Constructor

      /// <summary>
      /// Callback function for counting up from the time of transmission.
      /// </summary>
      /// <param name="source"></param>
      /// <param name="e"></param>
      private void OnCountUpEvent(object source, ElapsedEventArgs e)
      {
         duration = DateTime.Now.Subtract(currentTime);
         if ((duration.Seconds % environmentalModel.TransitionPeriod) == 0)
         {
            LeftButtonSwitchBetweenViews();
         }
         else
         {
            IsTransition = false;
         }
      }

      /// <summary>
      /// Environmental Models Properties
      /// </summary>
      #region Properties

      public ObservableCollection<StatusViewModelBase> DetailStatuses
      {
         private set
         {
            detailStatuses = value;
         }

         get
         {
            return detailStatuses;
         }
      }

      public bool IsTransition
      {
         private set;
         get;
      }

      /// <summary>
      /// Which environmental view index the view is set to.
      /// </summary>
      public int CurrentViewIndex
      {
         get
         {
            return currentViewIndex;
         }
         set
         {
            currentViewIndex = value;
            IsTransition = true;
            base.OnPropertyChanged("CurrentViewIndex");
            base.OnPropertyChanged("Name");
            base.OnPropertyChanged("Description");
            base.OnPropertyChanged("IconPath");            
            base.OnPropertyChanged("ToolTipDescription");
            DetailStatuses.Clear();
            DetailStatuses.Add(EnvironmentalItems[currentViewIndex]);
            base.OnPropertyChanged("DetailStatuses");
         }
      }

      /// <summary>
      /// Path to the icon image for this widget as indicated by the configuration file.
      /// </summary>
      public string IconPath
      {
         get
         {
            return environmentalModel.EnvironmentalItems[CurrentViewIndex].IconPath;
         }
      }

      /// <summary>
      /// Name of the widget as indicated by the configuration file.
      /// </summary>
      public string Name
      {
         get
         {
            return environmentalModel.EnvironmentalItems[CurrentViewIndex].Name;
         }
      }

      /// <summary>
      /// Description of the widget as indicated by the configuration file.
      /// </summary>
      public string Description
      {
         get
         {
            return environmentalModel.EnvironmentalItems[CurrentViewIndex].Description;
         }
      }

      /// <summary>
      /// Label for the detail button as indicated by the configuration file.
      /// </summary>
      public string DetailButtonDescription
      {
         get
         {
            return environmentalModel.EnvironmentalItems[CurrentViewIndex].DetailButtonDescription;
         }
      }

      /// <summary>
      /// Property to show or hide the inner model navigation button on the widget.
      /// </summary>
      public string IsMoreThanOneModel
      {
         get
         {
            if (environmentalModel.NumberOfSubModels > 1)
            {
               return Constants.VIEW_VISIBLE;
            }
            return Constants.VIEW_HIDDEN;
         }
      }

      /// <summary>
      /// Tooltip description for this widget as indicated by the configuration file.
      /// </summary>
      public string ToolTipDescription
      {
         get
         {
            return environmentalModel.EnvironmentalItems[CurrentViewIndex].ToolTipDescription;
         }
      }

      #endregion

      #region Commands

      /// <summary>
      /// Command binding to the left navigation button.
      /// </summary>
      public ICommand LeftNavigationButtonClickCommand
      {
         get
         {
            return new RelayCommand(param => this.LeftButtonSwitchBetweenViews());
         }
      }

      /// <summary>
      /// Command binding to the right navigation button.
      /// </summary>
      public ICommand RightNavigationButtonClickCommand
      {
         get
         {
            return new RelayCommand(param => this.RightButtonSwitchBetweenViews());
         }
      }

      /// <summary>
      /// For the left button switch view.
      /// </summary>
      private void LeftButtonSwitchBetweenViews()
      {
         if ((currentViewIndex - 1) < 0)
         {
            CurrentViewIndex = EnvironmentalItems.Count - 1;
         }
         else
         {
            --CurrentViewIndex;
         }
      }

      /// <summary>
      /// For the right button switch view.
      /// </summary>
      private void RightButtonSwitchBetweenViews()
      {
         if ((currentViewIndex + 1) >= EnvironmentalItems.Count)
         {
            CurrentViewIndex = 0;
         }
         else
         {++CurrentViewIndex;
         }
      }

      #endregion
   }

The inner view model for the inner UserControl, EnvironmentalDetailViewModel, is just a straight forward list of public properties for the inner UserControl to bind to and display.  All the other properties in the EnvironmentalViewModel.cs gets updated in the UI EXCEPT DetailStatuses.  The only way I can get the view in the MetricStatusDisplayControl.xaml to update the DetailStatuses via the timer is when I "new" the ObservableCollection for the DetailStatuses forcing an update to the UI.  However in doing so, I inadvertently introduced a slow memory leak which caused the program to crash after a long period of time.

Please advise on how to approach this...I've not been able to figure out how to make this animation without the memory leak.

Attached are images of what the same UserControl should look like when it's flipping through the inner models.  The labels on the main UserControl changes no problem, but the inner graph and main temperature display stays the same.

How Is Code Behind Used to Set Custom Tooltip for LineSeries?

$
0
0

Situation:

I am learning about customizing chart features in WPF (via C#) as I transition from MATLAB to .NET Framework. I have a question about further customization of the tooltips beyond what I learned from existing posts and from the this link:

http://istacee.wordpress.com/2013/03/19/wpf-toolkit-chart-custom-tooltip-on-lineseries-charts/

Question:

How may I use a method from code behind to display the desired string when one hovers over a point on the chart? More specifically, is it possible to use the method "MyComplexToMyString" to display the desired string?

Below is the code I have working so far. The vertical dots simply signify segments of charting code that are identical to what has been already displayed for the first line series.

The XAML extract:

<Window x:Class="TestApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Line Chart"
        xmlns:visualizationToolkit="clr-namespace:System.Windows.Controls.DataVisualization;assembly=System.Windows.Controls.DataVisualization.Toolkit"
        xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
        Height="675" Width="1200" >

<Grid Grid.Column="0" Margin="1">
<chartingToolkit:Chart Name="myLineChart" Height="auto" Width="auto" BorderBrush="#FFC0C0C0">
<chartingToolkit:LineSeries  Name="firstLineSeries"
Title="first curve"
ItemsSource="{Binding [0]}"
DependentValuePath="Value"
IndependentValuePath="Key"
IsSelectionEnabled="True">
<chartingToolkit:LineSeries.DataPointStyle>
<Style TargetType="chartingToolkit:DataPoint">
<Setter Property="Background" Value="Red" />
<Setter Property="BorderBrush" Value="Black" />
<Setter Property="BorderThickness" Value="5" />
<Setter Property="Width" Value="12" />
<Setter Property="Height" Value="12" />
<Setter Property="IsTabStop" Value="False" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="chartingToolkit:LineDataPoint">
<Grid x:Name="Root" Opacity="1">
<ToolTipService.ToolTip>
<StackPanel Margin="10,2,10,2">
<ContentControl Content="ABC:" FontWeight="Bold"/>
<ContentControl Content="{TemplateBinding IndependentValue}" />
<ContentControl Content="{TemplateBinding DependentValue}" />
</StackPanel>
</ToolTipService.ToolTip>
<Ellipse StrokeThickness="{TemplateBinding BorderThickness}" Stroke="{TemplateBinding BorderBrush}" Fill="{TemplateBinding Background}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</chartingToolkit:LineSeries.DataPointStyle>
</chartingToolkit:LineSeries>
</chartingToolkit:Chart>
<chartingToolkit:Chart Name="myLineChart" Height="auto" Width="auto" BorderBrush="#FFC0C0C0">
<chartingToolkit:LineSeries  Name="secondLineSeries"
Title="second curve"
ItemsSource="{Binding [1]}"
.
.
.
<StackPanel Margin="10,2,10,2">
<ContentControl Content="JKL:" FontWeight="Bold"/>
<ContentControl Content="{TemplateBinding IndependentValue}" />
<ContentControl Content="{TemplateBinding DependentValue}" />
</StackPanel>
</ToolTipService.ToolTip>
.
.
.
</chartingToolkit:LineSeries>
</chartingToolkit:Chart>
<chartingToolkit:Chart Name="myLineChart" Height="auto" Width="auto" BorderBrush="#FFC0C0C0">
<chartingToolkit:LineSeries  Name="secondLineSeries"
Title="second curve"
ItemsSource="{Binding [2]}"
.
.
.
<StackPanel Margin="10,2,10,2">
<ContentControl Content="XYZ:" FontWeight="Bold"/>
<ContentControl Content="{TemplateBinding IndependentValue}" />
<ContentControl Content="{TemplateBinding DependentValue}" />
</StackPanel>
</ToolTipService.ToolTip>
.
.
.
</chartingToolkit:LineSeries>
</chartingToolkit:Chart>
</Grid>

The C# Code Behind:

private void btnCreateChart_Click(object sender, RoutedEventArgs e)
{
GetChartCoordinates();
}

private void GetChartCoordinates()
{
((LineSeries)myLineChart.Series[0]).ItemsSource =
new KeyValuePair<double, double>[]{
new KeyValuePair<double,double>(0, 0),
new KeyValuePair<double,double> (6.4, 7.8)};
((LineSeries)myLineChart.Series[1]).ItemsSource =
new KeyValuePair<double, double>[]{
new KeyValuePair<double,double>(0, 0),
new KeyValuePair<double,double> (5.9, 2.3)};
((LineSeries)myLineChart.Series[2]).ItemsSource =
new KeyValuePair<double, double>[]{
new KeyValuePair<double,double>(0, 0),
new KeyValuePair<double,double> (8.1, 4.7)};
}

public string MyComplexToMyString(double myXAxisReal, double myYAxisImaginary)
{
string myFormattedMagnitudeAndAngle = "";
// ... do math and convert the x-axis and y-axis coordinates to a magnitude and an angle
return myFormattedMagnitudeAndAngle;
}


How to Merge cells in gridView columns following mvvm.

$
0
0

Hello, 

I have an app (following mvvm pattern) with columns as

Left ColumnRight Column
1
12
21
22
31
32

These columns resides in gridview which has Listview as the root. Is there any way i can merge the left column values to single values. 

Thanks.


Why does "Loading the projects is required to complete..." dialog box take SO LONG?

$
0
0

I'm working on a WPF app in VS 2012, now with Update 2. I've got a SQL Express database involved, which I'm accessing using entity framework 4.2. I've gone into the Data Sources and changed one of the fields in one of the tables to None, and tried dragging it onto the WPF window. Now I've got a dialog box that's been on there, stuck, for 30 minutes (yes, I'm timing it). Here's the dialog box:

Why is this taking so long???


Rod

Viewing all 18858 articles
Browse latest View live


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