I have the following Viewbox in MainWindow.Xaml:
<Viewbox x:Name="R1C1Viewbox" Grid.Row="1" Grid.Column="2"
Grid.ColumnSpan="1" Grid.RowSpan="1">
<Border x:Name="R1C1Border" BorderBrush="White" CornerRadius="3"
BorderThickness="2" Background="White"
Height="40" Width="40" Margin="0,3,3,0">
<Grid x:Name="R1C1Grid">
<TextBlock x:Name="R1C1TextBlock1" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Arial" FontWeight="Bold" Text="+" FontSize="22"></TextBlock>
<Polygon x:Name="R1C1LED"
Points="0,0 15,0 0,15"
Stroke="#FFED1C24"
StrokeThickness="1">
<Polygon.Fill>
<RadialGradientBrush>
<GradientStop Color="White" Offset="2.5"/>
<GradientStop Color="Black"/>
</RadialGradientBrush>
</Polygon.Fill>
</Polygon>
<Button x:Name="R1C1Button" Background="Transparent"
BorderBrush="Transparent">
</Button>
</Grid>
</Border>
</Viewbox>
In my code behind, I define 2 RadialGradientBrushes for the Polygon.Fill property:
public static RadialGradientBrush ledOn = new RadialGradientBrush();
public static RadialGradientBrush ledOff = new RadialGradientBrush();
ledOn.GradientStops.Add(new GradientStop(Colors.Red, .8));
ledOn.GradientStops.Add(new GradientStop(Colors.White, 0));
ledOff.GradientStops.Add(new GradientStop(Colors.White, 2.5));
ledOff.GradientStops.Add(new GradientStop(Colors.Black, 0));
If I load the viewbox only from MainWindow.xaml, I can use:
R1C1LED.Fill = ledOn;
or
R1C1LED.Fill = ledOff;
and the fill changes as expected. If I load the exact same xaml from a file using XamlReader(), the Viewbox displays exactly as expected but using the code behind to change the fill as above doesn't change the fill and no errors are generated.
Example code:
private void OnTest(object sender, RoutedEventArgs e)
{
var xaml =
#"<Window
xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
mc:Ignorable='d'
Title='WPF App' Height='450' Width='800'>
<StackPanel Orientation='Vertical'>
<Button x:Name='R1C1LED' Content='Load Data' />
</StackPanel>
</Window>";
var win = (Window)XamlReader.Parse(xaml);
var button = (Button)win.FindName("R1C1LED");
button.Background = Brushes.Red;
button.Click += (obj, args) => { MessageBox.Show("Hi!"); };
win.Show();
}
Related
I have an Image viewer implemented using ScrollViewer
.XAML
<ScrollViewer Name="viewImg" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" >
<Image Name="bigImage"
Source="/JoyOs.Media;component/img/Plugins/Photos/PHOTO.png"
PreviewMouseLeftButtonUp="ImageMouseLeftButtonUp"
PreviewMouseLeftButtonDown="ImageMouseLeftButtonDown"
PreviewMouseMove="ImageMouseMove" Stretch="Uniform"></Image>
</ScrollViewer>
ScrollViewer class .cs file
public partial class ImageList
{
private void ImageMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
var img = (Image)sender;
img.ReleaseMouseCapture();
}
private void ImageMouseMove(object sender, MouseEventArgs e)
{
var img = (Image)sender;
if (!img.IsMouseCaptured) return;
Vector v = _startImgMove - e.GetPosition(viewImg);
viewImg.ScrollToHorizontalOffset(_originImgMove.X - v.X);
viewImg.ScrollToVerticalOffset(_originImgMove.Y - v.Y);
}
private void ImageMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var img = (Image)sender;
img.CaptureMouse();
_startImgMove = e.GetPosition(viewImg);
_originImgMove = new Point(viewImg.HorizontalOffset, viewImg.VerticalOffset);
}
}
I want zoom features implemented in it.Hence I tried to use ZoomBorder.cs class from this.
How to use ZoomBorder.cswith ScrollViewer ?
I tried Without ScrollViewer with only ZoomBorder.cs like this.
<local:ZoomBorder x:Name="border" ClipToBounds="True" Background="Gray">
<Image Name="bigImage"
Source="/JoyOs.Media;component/img/Plugins/Photos/PHOTO.png"
PreviewMouseLeftButtonUp="ImageMouseLeftButtonUp"
PreviewMouseLeftButtonDown="ImageMouseLeftButtonDown"
PreviewMouseMove="ImageMouseMove" Stretch="Uniform"></Image>
</local:ZoomBorder>
I can't answer the question for ZoomBorder's, but I have implemented zoom functionality myself in a different way. I have a ViewBox, which I bind the ScaleTransform of to a value in my ViewModel. Changing the value in my ViewModel then causes the contents of the ViewBox to zoom in and out depending on the value.
<Viewbox x:Name="vwbxZoom" Stretch="None">
<Viewbox.LayoutTransform>
<ScaleTransform ScaleX="{Binding ZoomLevel.Value}"
ScaleY="{Binding ZoomLevel.Value}" />
</Viewbox.LayoutTransform>
</ViewBox>
Here is a quick example. You may use any control as content of the Viewbox
<DockPanel>
<Slider x:Name="ZoomSlider" DockPanel.Dock="Bottom" Minimum="0.05" Maximum="2">
</Slider>
<ScrollViewer HorizontalScrollBarVisibility="Auto">
<Viewbox Stretch="Uniform" VerticalAlignment="Center" HorizontalAlignment="Center">
<Border Width="2000" Height="2000">
<Border.Background>
<LinearGradientBrush StartPoint="0, 0.5" EndPoint="1, 0.5">
<GradientStop Color="Red" Offset="0.33"/>
<GradientStop Color="Green" Offset="0.66"/>
<GradientStop Color="Blue" Offset="1"/>
</LinearGradientBrush>
</Border.Background>
</Border>
<Viewbox.LayoutTransform>
<ScaleTransform ScaleX="{Binding ElementName=ZoomSlider, Path=Value}" ScaleY="{Binding ElementName=ZoomSlider, Path=Value}"/>
</Viewbox.LayoutTransform>
</Viewbox>
</ScrollViewer>
</DockPanel>
I have the following code :
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication3" xmlns:oxy="http://oxyplot.org/wpf"
xmlns:vm="clr-namespace:ViewModel;assembly=ViewModel"
Background="#FFDEDEDE"
WindowStyle="None"
AllowsTransparency="True"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d"
Title="Compression Test" Height="1080" Width="1920">
<Window.Resources>
<vm:MainViewModel x:Key="vmMain"
sampleCount="100" />
</Window.Resources>
<Grid x:Name="gridUI">
<StackPanel Orientation="Vertical">
<StackPanel Height="100">
<Border Background="#FF8986D3" Height="100" Margin="0,0,0,30" >
<TextBlock Text="COMPRESSION TEST" FontFamily="Sans-serif" FontSize="30" Foreground="#FFF9F9F9" VerticalAlignment="Center" FontWeight="Medium" HorizontalAlignment="Center"/>
</Border>
</StackPanel>
<StackPanel Orientation="Horizontal" Height="auto">
<Border BorderBrush="White" BorderThickness="2" >
<StackPanel Orientation="Vertical" Width="200" Height="1080">
<Label FontSize="24" FontFamily="Sans-serif" FontWeight="Medium" Name="doc" Foreground="White" Background="#FFA39AD8" Width="200" HorizontalContentAlignment="Center" Height="43">Files</Label>
<Border BorderBrush="#FFD4D4D4" BorderThickness="0.5" Grid.Row="3"></Border>
<StackPanel Name="sp_doc" Margin="0,10,0,0" >
<StackPanel Orientation="Horizontal" Name="sp_sample_button" Grid.Row="0" Grid.Column="0">
<Image Source="pack://application:,,,/Resources/413.png" Height="40" Width="40" UseLayoutRounding="True" MouseDown="sampleDropDown" Cursor="Hand" Margin="5,0,0,0" Name="up_arrow"/>
<Image Source="pack://application:,,,/Resources/412.png" Height="40" Width="40" UseLayoutRounding="True" MouseDown="sampleDropDown" Cursor="Hand" Margin="5,0,0,0" Name="down_arrow" Visibility="Collapsed"/>
<!--<Button x:Name="sss" Click="sampleDropDown">s</Button>-->
<Label FontSize="18" FontFamily="Sans-serif" FontWeight="Light" Name="sam" Foreground="White" Margin="10">Samples</Label>
</StackPanel>
<StackPanel Orientation="Vertical" Name="sp_s">
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Column="1" Grid.Row="1">
<Image Source="pack://application:,,,/Resources/413.png" Height="40" Width="40" UseLayoutRounding="True" RenderTransformOrigin="-0.,0.558" MouseDown="reportDropDown" Cursor="Hand" Margin="5,0,0,0" Name="up_arrow1"/>
<Image Source="pack://application:,,,/Resources/412.png" Height="40" Width="40" UseLayoutRounding="True" Cursor="Hand" Margin="5,0,0,0" Name="down_arrow1" Visibility="Collapsed" MouseDown="reportDropDown"/>
<!--<Button Click="reportDropDown">r</Button>-->
<Label FontFamily="Sans-serif" FontWeight="Light" Foreground="White" FontSize="18" Margin="10">Reports</Label>
</StackPanel>
<StackPanel Orientation="Vertical" Name="sp_r">
</StackPanel>
</StackPanel>
</StackPanel>
</Border>
<StackPanel Width="1781">
<StackPanel Orientation="Horizontal" Background="#FFFDFDFD" Height="111">
<TextBox Name="sampleCount" Text="{Binding sampleCount, Source={StaticResource vmMain}, UpdateSourceTrigger=PropertyChanged}" Width="200"></TextBox>
<Button Cursor="Hand" Height="75" Width="75" Style="{StaticResource CircleButton}" FontFamily="Sans-Serif" FontSize="25" Foreground="White" Click="NewSample_Click" Content="+" Margin="20,0,0,0" Background="#FFACAABF" />
<StackPanel Margin="20,19,0,0">
<Image Source="pack://application:,,,/Resources/file512.png" Height="75" Width="75" UseLayoutRounding="True" Margin="0,0,0,0" MouseDown="CreateReport_Click" Cursor="Hand" SnapsToDevicePixels="True"/>
</StackPanel>
<Image Source="pack://application:,,,/Resources/play1.png" Height="75" Width="75" UseLayoutRounding="True" Margin="20,18,0,18" MouseDown="CreateReport_Click" Cursor="Hand" SnapsToDevicePixels="True"/>
<Image Source="pack://application:,,,/Resources/1131.png" Height="75" Width="75" UseLayoutRounding="True" Margin="1340,0,0,0" MouseDown="CreateReport_Click" Cursor="Hand"/>
</StackPanel>
<Frame x:Name="newSampleFrame" Content="" HorizontalAlignment="center" VerticalAlignment="center" Width="934" Height="456" NavigationUIVisibility="Hidden" RenderTransformOrigin="0.408,0.5" Visibility="Collapsed"/>
<Frame x:Name="reportFrame" Content="" HorizontalAlignment="Center" Height="842" VerticalAlignment="Center" Width="595" Margin="0,100,0,0" NavigationUIVisibility="Hidden"/>
<Frame x:Name="graphFrame" Content="" HorizontalAlignment="Center" Height="456" VerticalAlignment="Center" Width="934" NavigationUIVisibility="Hidden" Visibility="Collapsed"/>
</StackPanel>
</StackPanel>
</StackPanel>
</Grid>
</Window>
MainViewModel.cs :
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ViewModel
{
public class MainViewModel : ObservableObject
{
public MainViewModel()
{
}
private string[] sampleName;
private string _sampleCount;
public Data obj2 = new Data();
public string this[int pos]
{
get
{
return sampleName[pos];
}
set
{
sampleName[pos] = value;
}
}
public string sampleCount
{
get
{
return _sampleCount;
}
set
{
if (value != _sampleCount)
{
_sampleCount = value;
OnPropertyChanged("sampleCount");
Console.WriteLine("Test");
Console.WriteLine(value);
obj2.sampleCount = value;
SaveFile.saveFileMain(obj2);
}
}
}
}
}
And I have the following code that create a textblock whenever I click on the OK button :
window2.xaml.cs:
private void Ok_Click(object sender, MouseButtonEventArgs e)
{
MainWindow win = (MainWindow)Application.Current.MainWindow;
int i = 1; // counter for the name of each new textblock
string name = String.Concat("sample", i);
// add textblok to the document list of new samples
if (File_name.Text != "")
{
TextBlock sampleText = new TextBlock();
sampleText.Text = File_name.Text;
sampleText.FontSize = 14;
sampleText.FontFamily = new FontFamily("Sans-serif");
sampleText.FontWeight = FontWeights.DemiBold;
sampleText.Margin = new Thickness(20,0,0,0);
sampleText.Name = name;
sampleText.PreviewMouseDown += new MouseButtonEventHandler(test1);
sampleText.Visibility = System.Windows.Visibility.Collapsed;
//binding
Binding myBinding = new Binding();
myBinding.Source =
myBinding.Path = new PropertyPath("sampleName");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
sampleText.SetBinding(TextBlock.TextProperty, myBinding);
Grid.SetColumn(sampleText, 0);
win.sp_s.Children.Add(sampleText);
// checking if the drop down of sample is already open, if so it will show the last textblock with pressing the arrow button.
var textblockSample = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (textblockSample.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}
}
i += 1; // increasing the loop of names by 1
this.Close();
}
Is it possible to use the same object that is initiated in xaml (vmMain) as a source for binding the textblock (sample text) to sampleName property?
Not sure why you don't set DataContext of your MainWindow to MainViewModel.
<Window.DataContext>
<StaticResourceExtension ResourceKey="vmMain" />
</Window.DataContext>
Or, you can even set DataContext via MainWindow's code behind, which you don't seem to intent to not keep it untouched.
Then to set binding source:
myBinding.Source = this.DataContext;
In the case you refused to set the DataContext, you still can:
myBinding.Source = this.FindResource("vmMain") as MainViewModel;
Not sure if I managed to solve your problem.
Edit
I just realised your binding is in window2. You should do this:
myBinding.Source = win.DataContext;
Similarly, myBinding.Source = this.FindResource("vmMain") as MainViewModel; should also be changed to myBinding.Source = win.FindResource("vmMain") as MainViewModel;.
This is provided you still have that MainWindow win = (MainWindow)Application.Current.MainWindow; line there.
I believe that what you are looking for is the resources property:
myBinding.Source = Resources["vmMain"];
Resource allows you to access the XAML-defined (or otherwise) resources for the current object - the window.
You can also access the resources of any FrameworkElement in the same manner.
EDIT: I hadn't noted the fact that the vmMain was in a different class. With this in mind, no there is no way to reference that object directly from Window2 as there may be multiple MainWindows so you'd have to pick which MainWindow instance the vmMain should be taken from.
What you can do, however is create vmMain in your Application object (App.xaml). This would then share that object across all FrameworkElements in your application. To access this you could use
myBinding.Source = Application.Currennt.Resources["vmMain"];
I know there are a lot of question like this in the web, but believe me I spent on this a lot of hours and I still not success, I really will glad for any help!
I loading various images in run time and I want to show them in list box (small images, then the user should click on one of them and show him in real size).
my code is:
public partial class MainWindow : Window
{
int imageNumber = 0;
public List<String> ImagePath = new List<String>();
public MainWindow()
{
InitializeComponent();
lb_Images.ItemsSource = ImagePath;
}
private void bu_addImage_Click(object sender, RoutedEventArgs e)
{
addImageToListBox();
}
private void addImageToListBox()
{
imageNumber++;
if (imageNumber == 4) imageNumber = 0;
string directoryPath = AppDomain.CurrentDomain.BaseDirectory;
// load input image
string ImageFilename = directoryPath + "img";
ImageFilename += imageNumber.ToString();
ImageFilename += ".jpg";
ImagePath.Add(ImageFilename);
}
}
and the xaml is:
<Window x:Class="forQuestionWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="216" Width="519">
<Window.Resources>
<DataTemplate x:Key="ImageGalleryDataTemplate">
<Grid>
<Border BorderBrush="#FFFF9800" BorderThickness="1" Width="120" Height="120" Padding="5" Margin="5" CornerRadius="6">
<!--Bind Image Path in Image Control-->
<Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center">
<!--View Large Image on Image Control Tooltip-->
<Image.ToolTip>
<Grid>
<Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center" Height="200" Width="200"></Image>
</Grid>
</Image.ToolTip>
</Image>
</Border>
</Grid>
</DataTemplate>
<ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
<!--Display Images on UniformGrid Panel-->
<UniformGrid Rows="1" Columns="25" HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
</ItemsPanelTemplate>
</Window.Resources>
<Grid>
<Canvas Height="177" HorizontalAlignment="Left" Name="canvas1" VerticalAlignment="Top" Width="497">
<ListBox Canvas.Left="6" Canvas.Top="5" Height="166" Name="lb_Images" Width="441"
BorderBrush="{x:Null}" DataContext="{Binding Source={StaticResource ImageGalleryDataTemplate}}"
ItemsSource="{Binding Source={StaticResource ImageGalleryItemsPanelTemplate}}">
</ListBox>
<Button Canvas.Left="453" Canvas.Top="26" Content="Add" Height="64" Name="bu_addImage" Width="38" Click="bu_addImage_Click" />
</Canvas>
</Grid>
</Window>
I know that the list box updated when I add image path to the list because if I debug I found some items under lb_Images.items, but I show nothing.
I'll glad for any help! thank you!!
Some notes
DataContext for ListBox it's not necessary, then you set ItemSource. Instead of set the ItemTemplate
In DataTemplate remove the {Binding ImagePath}, instead of write {Binding}, because in this case the elements of the DataTemplate inherit DataContext.
When you add new items to ListBox.Items, you must call ListBox.Items.Refresh() or use the ObservableCollection<T>, because:
ObservableCollection represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
Try this example:
XAML
<Window.Resources>
<DataTemplate x:Key="ImageGalleryDataTemplate">
<Grid>
<Border BorderBrush="#FFFF9800" BorderThickness="1" Width="120" Height="120" Padding="5" Margin="5" CornerRadius="6">
<Image Source="{Binding}" Stretch="Fill" HorizontalAlignment="Center">
<Image.ToolTip>
<Grid>
<Image Source="{Binding}" Stretch="Fill" HorizontalAlignment="Center" Height="200" Width="200" />
</Grid>
</Image.ToolTip>
</Image>
</Border>
</Grid>
</DataTemplate>
<ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
<UniformGrid Rows="1" Columns="25" HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
</ItemsPanelTemplate>
</Window.Resources>
<Grid>
<Canvas Height="177" HorizontalAlignment="Left" Name="canvas1" VerticalAlignment="Top" Width="497">
<ListBox Canvas.Left="6" Canvas.Top="5" Height="166" Name="lb_Images" Width="441"
ItemTemplate="{StaticResource ImageGalleryDataTemplate}"
ItemsSource="{Binding Path=ImagePath}">
</ListBox>
<Button Canvas.Left="453" Canvas.Top="26" Content="Add" Height="64" Name="bu_addImage" Width="38" Click="bu_addImage_Click" />
</Canvas>
</Grid>
Code-behind
public partial class MainWindow : Window
{
int imageNumber = 0;
public List<String> ImagePath = new List<String>();
public MainWindow()
{
InitializeComponent();
lb_Images.ItemsSource = ImagePath;
}
private void bu_addImage_Click(object sender, RoutedEventArgs e)
{
addImageToListBox();
}
private void addImageToListBox()
{
imageNumber++;
if (imageNumber == 4) imageNumber = 0;
string directoryPath = AppDomain.CurrentDomain.BaseDirectory;
// load input image
string ImageFilename = directoryPath + "img";
ImageFilename += imageNumber.ToString();
ImageFilename += ".jpg";
ImagePath.Add(ImageFilename);
lb_Images.Items.Refresh();
}
}
I'm using Time Picker from wpfToolkit.extended in WPF application.
When I select a time in the dropdrownlist everything works the way it should. This is the namespace of the toolkit.
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
This is the xaml for the timepicker
<Controls:MetroWindow
x:Class="TimeSheet.DayView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:e="http://schemas.microsoft.com/developer/msbuild/2003"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:TimeSheet.Views.DataTemplateSpace"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
x:Name="MainWin"
Title="DayView" Width="596" Height="596">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colours.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" />
<ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- <Style x:Key="ColoringStyle" TargetType="{x:Type ListBoxItem}">
<EventSetter Event="MouseDoubleClick" Handler="ListBoxItem_MouseDoubleClick"/>
<Style.Triggers>
<DataTrigger Binding="{Binding isSynced}" Value="true">
<Setter Property="Background" Value="Gold"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding isSynced}" Value="false">
<Setter Property="Background" Value="Aqua"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>-->
<!-- Default DataTemplate -->
<DataTemplate x:Key="DefaultDataTemplate" >
<StackPanel Orientation="Horizontal" Width="596">
<TextBlock Text="{Binding ClientNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="145"/>
<TextBlock Text="{Binding ApplicationNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="90"/>
<TextBlock Text="{Binding StartTimeBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="100"/>
<TextBlock Text="{Binding StopTimeBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="60"/>
<TextBlock Text="{Binding TaskNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="71"/>
<TextBlock Text="{Binding ProjectNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="130"/>
</StackPanel>
</DataTemplate>
<!-- Editable DataTemplate -->
<DataTemplate x:Key="EditableDataTemplate">
<StackPanel Orientation="Horizontal" Width="596">
<!--<ComboBox x:Name="ClientComboBox" SelectionChanged="ClientComboBoxChanged" ItemsSource="{Binding Path=clientList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name" SelectedItem="{Binding ClientNameBindingClass, Mode=OneWayToSource}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="145"/>-->
<TextBox Text="{Binding ClientNameBinding,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="145"/>
<TextBox Text="{Binding ApplicationNameBinding}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="90"/>
<xctk:TimePicker Name="StartPicker" TextBoxBase.TextChanged="StartPicker_TextChanged" Value="{Binding StartValue, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="100" EndTime="11:59:0"/>
<xctk:TimePicker Name="EndPicker" TextBoxBase.TextChanged="EndPicker_TextChanged" Value="{Binding EndValue, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="60" EndTime="11:59:0"/>
<TextBox Text="{Binding TaskNameBinding}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="71"/>
<ComboBox x:Name="ProjectComboBox" ItemsSource="{Binding Path=projectList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name" SelectedItem="{Binding ProjectNameBindingClass, Mode=OneWayToSource}" Width="130" Background="Yellow" BorderThickness="0"/>
</StackPanel>
</DataTemplate>
<!-- DataTemplate Selector -->
<l:DayViewListDataTemplateSelector x:Key="templateSelector"
DefaultDataTemplate="{StaticResource DefaultDataTemplate}"
EditableDataTemplate="{StaticResource EditableDataTemplate}"/>
</ResourceDictionary>
</Window.Resources>
<Viewbox Stretch="Fill" Width="{Binding Width, ElementName=MainWin}" Height="{Binding Height, ElementName=MainWin}">
<Grid Margin="0,0,0,-4" Background="#FF3399FF" Height="557">
<Button x:Name="BackButton" Style="{DynamicResource MetroCircleButtonStyle}" Content="<---" Foreground="Blue" Click="BackButton_Click" Margin="7,2,524,491"/>
<Button x:Name="TimerButton" Width="124" Height="46" Click="TimerButton_Click" Margin="172,12,300,499">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
<GradientStop Color="#FF5B6CB8"/>
</LinearGradientBrush>
</Button.Background>
</Button>
<Label x:Name="monthLabel" Content="May" RenderTransformOrigin="2.34,0.545" FontFamily="Times New Roman" FontSize="20" Margin="431,2,90,522"/>
<Label x:Name="dayDateLabel" Content="Friday, 27" RenderTransformOrigin="0.446,0.226" FontFamily="Times New Roman" FontSize="36" FontWeight="Bold" Margin="376,35,38,467"/>
<StackPanel Orientation="Horizontal" Margin="-1,93,1,434" RenderTransformOrigin="1.155,0.47" Height="25">
<TextBox Text="Client" HorizontalContentAlignment="Center" Width="145" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/>
<TextBox Text="Application" HorizontalContentAlignment="Center" Width="90" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/>
<TextBox Text="StartTime" HorizontalContentAlignment="Center" Canvas.Left="148" Canvas.Top="86" Width="100" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" RenderTransformOrigin="0.5,0.5" VerticalContentAlignment="Center"/>
<TextBox Text="StopTime" HorizontalContentAlignment="Center" Width="60" RenderTransformOrigin="0.471,0.692" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/>
<TextBox Text="Task" HorizontalContentAlignment="Center" Canvas.Left="378" Canvas.Top="86" Width="130" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/>
<TextBox Text="Project" HorizontalContentAlignment="Center" Width="71" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/>
</StackPanel>
<ListBox x:Name="listBox1" ItemsSource="{Binding}" Margin="0,131,0,59" ItemTemplateSelector="{StaticResource templateSelector}" SelectionMode="Single">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="MouseDoubleClick" Handler="listBox1_MouseDoubleClick">
</EventSetter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
<Button x:Name="SyncEntry" Content="Sync All" HorizontalAlignment="Left" Margin="476,498,0,0" VerticalAlignment="Top" Width="95" Click="SyncEntry_Click">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
<GradientStop Color="#FF5256AC"/>
</LinearGradientBrush>
</Button.Background>
</Button>
<Button x:Name="EditButton" Content="Edit" HorizontalAlignment="Left" Margin="393,498,0,0" VerticalAlignment="Top" Width="75" Click="EditButton_Click">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="White" Offset="1"/>
<GradientStop Color="#FF5256AC"/>
</LinearGradientBrush>
</Button.Background>
</Button>
<Button x:Name="CustomButton" Content="Add" HorizontalAlignment="Left" Margin="0,70,0,0" VerticalAlignment="Top" Width="75" FontSize="12" Height="20" FontWeight="Normal" Click="CustomButton_Click"/>
</Grid>
</Viewbox>
I've seen solution for this here
but when I write C# code-
public partial class DayView : MetroWindow, INotifyPropertyChanged
{
private DateTime currentDateForWindow;
public List<Harvest_Project> projectList{get;set;}
public List<Harvest_Client> clientList {get; set;}
public Harvest_Project selectedProjectid {get; set;}
public Harvest_Client selectedClientid {get; set;}
public string ElementName { get; set; }
public DateTime StartValue { get; set; }
public DateTime EndValue { get; set; }
public DayView(DateTime s)
{
InitializeComponent();
this.DataContext = this;
Globals._globalController.setDayViewWindow(this);
currentDateForWindow = s;
dayDateLabel.Content = s.DayOfWeek + ", " + s.Day;
monthLabel.Content = s.ToString("MMMM");
if(Globals._globalController.win32Manager.isTimerRunning)
TimerButton.Content = "Stop";
else
TimerButton.Content = "Start";
listBox1.Items.Clear();
listBox1.MouseDoubleClick += new MouseButtonEventHandler(listBox1_MouseDoubleClick);
clientList = Globals._globalController.harvestManager._CLIENTLIST;
projectList = Globals._globalController.harvestManager._PROJECTLIST;
Globals._globalController.fetchAndPopulateForDate(currentDateForWindow);
Globals.ni2 = new NotifyIcon();
Globals.ni2.Icon = TimeSheet.Properties.Resources.DayViewIcon;
Globals.ni2.Visible = true;
Globals.ni2.Click +=
delegate(object sender, EventArgs args)
{
this.Show();
this.WindowState = WindowState.Normal;
};
}
protected override void OnStateChanged(EventArgs e)
{
if (WindowState == System.Windows.WindowState.Minimized)
{
this.Hide();
Globals.ni2.BalloonTipTitle = "DayView";
Globals.ni2.BalloonTipText = "This is Day window";
Globals.ni2.Visible = true;
Globals.ni2.ShowBalloonTip(500);
base.OnStateChanged(e);
}
}
public void addHarvestEntrytoView(Harvest_TimeSheetEntry entry)
{
listBox1.Items.Add(entry);
}
public void addHarvestEntrytoView(List<Harvest_TimeSheetEntry> entry)
{
foreach (Harvest_TimeSheetEntry x in entry)
listBox1.Items.Add(x);
}
private void BackButton_Click(object sender, RoutedEventArgs e)
{
Globals.ni2.Visible=false;
this.Hide();
Globals._globalController.getMonthViewWindow.Show();
Globals.ni1.Visible = true;
}
private void TimerButton_Click(object sender, RoutedEventArgs e)
{
if (!Globals._globalController.win32Manager.isTimerRunning)
{
Globals._globalController.win32Manager.startTimer();
this.TimerButton.Content = "Stop";
}
else
{
Globals._globalController.win32Manager.stopTimer();
this.TimerButton.Content = "Start";
}
}
private void SyncEntry_Click(object sender, RoutedEventArgs e)
{
//Submit All unsynced Entries
foreach(Harvest_TimeSheetEntry item in listBox1.Items)
{
if (!item.isSynced)
{
if (item.ProjectNameBinding == "Select Project" && item.ClientNameBinding == "Select Client")
System.Windows.MessageBox.Show("Please select you Project and Client");
else
//Check if something is selected in selectedProjectItem For that item
Globals._globalController.harvestManager.postHarvestEntry(item);
System.Windows.MessageBox.Show("Entry posted");
}
}
}
private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
//Submit clicked Entry
if (sender is ListBoxItem)
{
ListBoxItem item = (ListBoxItem)sender;
Harvest_TimeSheetEntry entryToPost = (Harvest_TimeSheetEntry)item.DataContext;
if (!entryToPost.isSynced)
{
//Check if something is selected in selectedClientItem and selectedProjectItem For that items
if (entryToPost.ClientNameBinding == "Select Client" || entryToPost.ProjectNameBinding == "Select Project")
System.Windows.MessageBox.Show("Please select you Project and Client");
else
{
Globals._globalController.harvestManager.postHarvestEntry(entryToPost);
System.Windows.MessageBox.Show("Entry posted");
DataTemplate tmpl = (DataTemplate)this.FindResource("DefaultDataTemplate");
listBox1.ItemTemplate = tmpl;
}
}
else
{
//Already synced.. Make a noise or something
System.Windows.MessageBox.Show("Already Synced;TODO Play a Sound Instead");
}
}
}
private void EditButton_Click(object sender, RoutedEventArgs e)
{
foreach (Harvest_TimeSheetEntry item in listBox1.Items)
{
if (item.isSynced)
{
item.isSynced = false;
listBox1.ItemTemplate = (DataTemplate)this.FindResource("EditableDataTemplate");
this.EditButton.Content = "Done Editing";
}
else
{
listBox1.ItemTemplate = (DataTemplate)this.FindResource("DefaultDataTemplate");
this.EditButton.Content = "Edit";
Globals._globalController.harvestManager.postHarvestEntry(item);
System.Windows.MessageBox.Show("Entry posted");
}
}
}
private void CustomButton_Click(object sender, RoutedEventArgs e)
{
Globals.ni2.Visible=false;
CustomView c = new CustomView(Globals._globalController.getDayViewWindow);
c.Show();
this.Hide();
Globals.ni3.Visible = true;
}
private void StartPicker_TextChanged(object sender, TextChangedEventArgs e)
{
StartPicker.Focus();
}
private void EndPicker_TextChanged(object sender, TextChangedEventArgs e)
{
EndPicker.Focus();
}
protected virtual void OnPropertyChanged(String time)
{
if (System.String.IsNullOrEmpty(time))
{
return;
}
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(time));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
It shows error as "StartPicker and EndPicker does not exist in current context".
Suggest the ways to solve this error.
Xaml-
<Grid>
<xctk:TimePicker Name="StartPicker" TextBoxBase.TextChanged="StartPicker_TextChanged" Value="{Binding StartTimeBinding, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="100" Height="50" EndTime="11:59:0"/>
<xctk:TimePicker Name="EndPicker" TextBoxBase.TextChanged="EndPicker_TextChanged" Value="{Binding StopTimeBinding, ElementName=MainWin1, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="60" Height="50" EndTime="11:59:0"/>
</Grid>
Code-Behind your Xaml in Xaml.cs
private void EndPicker_TextChanged(object sender, TextChangedEventArgs e)
{
StartPicker.Focus(); // shows error at TimePicker Name(i.e StartPicker)
}
private void StartPicker_TextChanged(object sender, TextChangedEventArgs e)
{
EndPicker.Focus(); // shows error at EndPicker
}
Try it this way:
private void StartPicker_TextChanged(object sender, TextChangedEventArgs e)
{
TimePicker tp = sender as TimePicker;
if(tp != null)
{
tp.Focus();
}
}
private void EndPicker_TextChanged(object sender, TextChangedEventArgs e)
{
TimePicker tp = sender as TimePicker;
if(tp != null)
{
tp.Focus();
}
}
Of course you can have only one function and point from both timepickers to this function:
private void TimePicker_TextChanged(object sender, TextChangedEventArgs e)
{
TimePicker tp = sender as TimePicker;
if(tp != null)
{
tp.Focus();
}
}
and then in the xaml:
<xctk:TimePicker Name="StartPicker" TextBoxBase.TextChanged="TimePicker_TextChanged" Value="{Binding StartValue, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="100" EndTime="11:59:0"/>
<xctk:TimePicker Name="EndPicker" TextBoxBase.TextChanged="TimePicker_TextChanged" Value="{Binding EndValue, ElementName=MainWin, UpdateSourceTrigger=PropertyChanged}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="60" EndTime="11:59:0"/>
The following code creates 2 tabs on the click of a button, but does not display any content. I'm still learning this and want to know what the mistake is.
Code behind
public void button2_Click(object sender, RoutedEventArgs e)
{
popUp1.IsOpen = false;
Canvas canvas4 = new Canvas();
ScrollViewer viewer4 = new ScrollViewer();
viewer4.Content = canvas4;
string txtfl = File.ReadAllText(textBox1.Text);
TextBlock txbl1 = new TextBlock();
txbl1.Text = txtfl;
canvas4.Children.Add(txbl1);
TabItem newTab1 = new TabItem();
newTab1.Header = "Text File";
newTab1.Content = viewer4;
tabctrl1.Items.Add(newTab1);
tabctrl1.SelectedItem = newTab1;
Brush br = new SolidColorBrush(Colors.White);
Canvas canvas2 = new Canvas();
canvas2.Background = br;
ScrollViewer viewer2 = new ScrollViewer();
viewer2.Content = canvas2;
TabItem newTab2 = new TabItem();
newTab2.Header = "Test";
newTab2.Content = viewer2;
tabctrl1.Items.Add(newTab2);
}
TabControl is created using XAML
XAML
<Window ... >
<Grid>
<Popup Name="popUp1" Width="500" Height="300" Placement="Center" IsEnabled="False" IsOpen="False">
<Canvas x:Name="myCanvas1" Width="500" Height="300" Visibility="Visible">
<Button Content="Button" Height="38" HorizontalAlignment="Left" Margin="12,71,0,0" Name="button1" VerticalAlignment="Top" Width="151" Click="button2_Click" />
</Canvas>
</Popup>
<TabControl Name="tabctrl1" Width="1345" Height="28" Margin="0,24,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" BorderThickness="2">
<TabControl.Background>
<LinearGradientBrush EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#FF3A60AD" Offset="0.528"/>
<GradientStop Color="#FF6A85D8" Offset="0.01"/>
</LinearGradientBrush>
</TabControl.Background>
</TabControl>
</Grid>
</Window>
Hi the reason your code does not appear to work is because the Height of the tab control is set to 28.
Try changing it to 280, you should then be able to see the content.
<TabControl Name="tabctrl1" Width="1345" Height="280" Margin="0,24,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" BorderThickness="2">