I've got code where there's a string variable in MainWindow called "repeatNumber" - there's also two buttons in MainWindow. btn2 should open up a new window 'otherwindow' that has the repeatNumber string in it and displays the picture.
'Window1' does not contain a definition for 'getRepeatedNumber' and no extension method 'getRepeatedNumber' accepting a first argument of type 'Window1' could be found.
Can anyone help me with this? Can this be fixed without using MVVM? Code bellow:
Mainwindow.cs
public partial class MainWindow : Window
{
private string repeatNumber;
public MainWindow()
{
InitializeComponent();
string[] assignments = new string[] { "https://cdn2.iconfinder.com/data/icons/animals/48/Turtle.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Butterfly.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Dolphin.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Elephant.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Hippopotamus.png", "https://cdn2.iconfinder.com/data/icons/animals/48/Panda.png" };
Random rnd = new Random();
string[] randomingArray = assignments.OrderBy(x => rnd.Next()).ToArray();
List<Images> animals = new List<Images>();
for (int i = 1; i < 100; i++)
{
if (i == 9)
{
repeatNumber = randomingArray[i % randomingArray.Length];
animals.Add(new Images() { Source = repeatNumber, Number = i });
}
else if ((i % 9) == 0)
{
animals.Add(new Images() { Source = repeatNumber, Number = i });
}
else
{
animals.Add(new Images() { Source = randomingArray[i % rnd.Next(1, 5)], Number = i });
}
ItemsControl1.ItemsSource = animals;
}
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("test");
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
Window1 otherwindow = new Window1();
otherwindow.Show();
string value = otherwindow.getRepeatedNumber; <--- This line gives me the error
}
}
class Images
{
public int Number { get; set; }
public string Source { get; set; }
}
Mainwindow.xaml
<Grid>
<ListBox x:Name="ItemsControl1">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="5">
</UniformGrid>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="3" Width="Auto" Height="Auto">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Number}"/>
<Image Source="{Binding Source}" Margin="0,0,5,0"/>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid>
<Button x:Name="btn1" Click="btn1_Click" Height="20" VerticalAlignment="Bottom" Margin="127,0,316,0" Content="Instruction"></Button>
<Button x:Name="btn2" Click="btn2_Click" Height="20" VerticalAlignment="Bottom" Margin="300,0,109,0" Content="Results" Width="74"></Button>
</Grid>
</Grid>
Window1.cs
public class Window2 : Window
{
public string getRepeatedNumber { get; set; }
public Window2(string repeatNumber)
{
getRepeatedNumber = repeatNumber;
}
}
and Window1.xaml is just
<Grid>
</Grid>
Related
I'm making a WPF Application with MVVM pattern.
It's that I click a button many times and if I click Subbutton, it shows SubWindow with many Tabs.
Tab count is the same to click times.
But I want contain items in one Tab.
And click times is not the same always.
How should edit my code?
//view
<Grid>
<Button Content="CountUp" HorizontalAlignment="Left" Height="76" Margin="72,57,0,0" VerticalAlignment="Top" Width="135" Click="OnClickCountUp"/>
<Button Content="OpenSubWindow" HorizontalAlignment="Left" Height="74" Margin="269,202,0,0" VerticalAlignment="Top" Width="123" Click="OnClicOpenSubWindow"/>
<Label Content="Count : " HorizontalAlignment="Left" Height="28" Margin="254,73,0,0" VerticalAlignment="Top" Width="53"/>
<Label Content="{Binding CountVal}" HorizontalAlignment="Left" Height="28" Margin="307,73,0,0" VerticalAlignment="Top" Width="67"/>
</Grid>
//ViewModel
public class MainViewModel : INotifyPropertyChanged
{
private string count;
public string CountVal
{
get { return count; }
set
{
count = value;
NotifyPropertyChanged("CountVal");
}
}
public ObservableCollection<TabItemData> TabItems { get; set; } = new ObservableCollection<TabItemData>();
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
public class TabItemData
{
public string Header { get; set; }
public ObservableCollection<CheckBox> Content { get; set; }
}
//Codebehind
public partial class MainWindow : Window
{
private MainViewModel mViewmodel;
int count = 0;
public MainWindow()
{
InitializeComponent();
mViewmodel = new MainViewModel();
this.DataContext = mViewmodel;
}
private void OnClicOpenSubWindow(object sender, RoutedEventArgs e)
{
Window1 window1 = new Window1(mViewmodel);
window1.Show();
}
private void OnClickCountUp(object sender, RoutedEventArgs e)
{
count++;
ObservableCollection<CheckBox> items = new ObservableCollection<CheckBox>();
for (int i = 0; i <= count; i++)
{
CheckBox checkBox = new CheckBox();
checkBox.IsChecked = false;
checkBox.Content = count.ToString();
items.Add(checkBox);
}
mViewmodel.CountVal = count.ToString();
mViewmodel.TabItems.Add(new TabItemData() { Header = count.ToString(), Content = items });
}
}
//SubWindow's View
<Grid>
<TabControl ItemsSource="{Binding TabItems}">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<CheckBox Content="{Binding Content}" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
</Grid>
//SubWindow's Codebehind
public partial class Window1 : Window
{
public Window1(MainViewModel pMainViewModel)
{
InitializeComponent();
this.DataContext = pMainViewModel;
}
}
And there are supplements.
#I want use the checkbox as item in Tab. So I don't want change as possibly.
#If I can, I want add Tabs each 5 items. If you give me with that code, I'm very glad. (For Example, page1 contains item1, 2, 3, 4 and 5. page2 contains item6, 7... and so on.)
I am writing a Windows Phone 8.1 App.
It has GridView, First row must show 2 items, 2nd and 3rd row must show 3 items each and rest rows must show 4 items. I am trying to use VariableSizedGridView:
Click Here to View Image
but my items are being shown in 1 column like a long list.
Click to view ScreenShot
XAML:
<UserControls:VariableSizedGridView x:Name="ModelRingsGridViewVariable" HorizontalAlignment="Stretch">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid ItemHeight="180"
ItemWidth="20" Orientation="Horizontal"/>
<!--ItemWidth="{Binding ElementName=modelPage, Path=WidthCalculator}"-->
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemTemplate>
<DataTemplate>
<Grid Background="White" Margin="2">
<StackPanel Orientation="Vertical">
<Image Height="100" VerticalAlignment="Top" Source="{Binding ImageLocation}" Stretch="Fill"></Image>
<Grid Background="{StaticResource LightGreenBlueColor}" VerticalAlignment="Bottom"
HorizontalAlignment="Stretch">
<TextBlock Margin="0,8,0,8" VerticalAlignment="Center"
HorizontalAlignment="Center" FontSize="18"
Text="{Binding ImageName}" Foreground="White"></TextBlock>
</Grid>
</StackPanel>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</UserControls:VariableSizedGridView>
C#:
private void GenerateGridViewData()
{
ModelRingsGridViewVariable.Width = Window.Current.Bounds.Width;
ObservableCollection<ModelClass> ModelRingsGridViewData = new ObservableCollection<ModelClass>();
int j = 1;
Uri location = new Uri("ms-appx:///Images/TestImages/TestImageRing.png", UriKind.RelativeOrAbsolute);
for (int i=0; i<20;i++)
{
if(i==0 || i== 1)
{
ModelRingsGridViewData.Add(new ModelClass { ImageName = "RING " + j.ToString(), ImageLocation = location, ColSpan=6 });
}
else if(i== 2 || i==3 || i==4)
{
ModelRingsGridViewData.Add(new ModelClass { ImageName = "RING " + j.ToString(), ImageLocation = location, ColSpan=4 });
}
else
{
ModelRingsGridViewData.Add(new ModelClass { ImageName = "RING " + j.ToString(), ImageLocation = location,ColSpan=3 });
}
j++;
}
ModelRingsGridViewVariable.ItemsSource = ModelRingsGridViewData;
}
Model:
public class ModelClass
{
public Uri ImageLocation { get; set; }
public String ImageName { get; set; }
public int ColSpan { get; set; }
}
VariableSizedGridView.cs:
public class VariableSizedGridView : GridView
{
protected override void PrepareContainerForItemOverride(DependencyObject element,
object item)
{
try
{
dynamic localItem = item;
// element.SetValue(VariableSizedWrapGrid.RowSpanProperty, localItem.RowSpan);
element.SetValue(VariableSizedWrapGrid.ColumnSpanProperty, localItem.ColSpan);
}
catch
{
// element.SetValue(VariableSizedWrapGrid.RowSpanProperty, 1);
element.SetValue(VariableSizedWrapGrid.ColumnSpanProperty, 1);
}
base.PrepareContainerForItemOverride(element, item);
}
}
I have no Binding errors in my output window.
I want to bind text from a file(s) to one/many avalonEdit controls via MVVM.
How can I do that, because its not working the way I tried?!
VIEW
>
<Window.Resources>
<DataTemplate x:Key="NormalTemplate">
<Expander Margin="0" Header="{Binding FileName}">
<!--<TextBox TextWrapping="Wrap" AcceptsReturn="True" IsReadOnly="True" Text="{Binding Content}" Margin="0"/>-->
<avalonEdit:TextEditor Document="{Binding Document, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></avalonEdit:TextEditor>
</Expander>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40px"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid Background="Orange">
<StackPanel Orientation="Horizontal">
<Button>Run</Button>
<Button Command="{Binding SaveCommand}">Save</Button>
</StackPanel>
</Grid>
<Grid Grid.Row="1">
<ScrollViewer ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ItemsControl ItemsSource="{Binding ErrorLogs}" HorizontalContentAlignment="Stretch" ItemTemplate="{DynamicResource NormalTemplate}" />
</ScrollViewer>
</Grid>
</Grid>
</Window>
VIEWMODEL
public class ErrorLogViewModel : BaseViewModel
{
public string FileName { get; set; }
public string Content { get; set; }
private TextDocument _document = null;
public TextDocument Document
{
get { return this._document; }
set
{
if (this._document != value)
{
this._document = value;
RaisePropertyChanged("Document");
}
}
}
}
public class MainViewModel : BaseViewModel
{
public MainViewModel()
{
GetErrorLogs();
SaveCommand = new RelayCommand(Save);
}
public RelayCommand SaveCommand { get; private set; }
private void Save()
{
var text = ErrorLogs[0].Document.Text;
// I get at least the Original loaded text
}
private void GetErrorLogs()
{
for (int i = 0; i < 30; i++)
{
using (FileStream fs = new FileStream("text.txt", FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (StreamReader reader = FileReader.OpenStream(fs, Encoding.UTF8))
{
var doc = new TextDocument(reader.ReadToEnd());
var e = new ErrorLogViewModel { FileName = "ErrorLog " + i, Document = doc };
ErrorLogs.Add(e);
}
}
}
}
private ObservableCollection<ErrorLogViewModel> _errorLogs = new ObservableCollection<ErrorLogViewModel>();
public ObservableCollection<ErrorLogViewModel> ErrorLogs
{
get { return _errorLogs; }
set
{
_errorLogs = value;
this.RaisePropertyChanged("ErrorLogs");
}
}
}
I have looked at that sample were MVVM is introduced:
http://www.codeproject.com/Articles/570313/AvalonDock-Tutorial-Part-AvalonEdit-in-Avalo
I do the same binding actually when I load a text file but my text is just not shown :/
You can find here a repro visual studio solution:
http://www.file-upload.net/download-9067428/ExpanderTest.7z.html
I want to generate ListItemBox using DataTemplate but items are not generating. Please guide me where is the mistake. I have following code in MainWindow.xaml.
<Window x:Class="Offline_Website_Downloader.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:bd="clr-namespace:Offline_Website_Downloader"
Title="Offline Website Downloader" Background="#f5f6f7" Height="500" Width="800"
WindowStartupLocation="CenterScreen">
<Window.Resources>
<bd:BindingController x:Key="BindingControllerKey" />
<DataTemplate x:Key="DownloadedWebsitesListBox">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal" Width="Auto">
<TextBlock FontWeight="Bold" FontSize="18" Width="480">
<Hyperlink NavigateUri="http://google.com">
<Label Content="{Binding Path=WebsiteTitle}" />
</Hyperlink>
</TextBlock>
<TextBlock Width="132" TextAlignment="right">
<TextBlock Text="Remaining Time: "/>
<TextBlock Name="TimeRemaining" Text="js"/>
</TextBlock>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ProgressBar Name="progress1" Maximum="100" Minimum="0" Value="30" Background="#FFF" Width="612" Height="10" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock HorizontalAlignment="Left" Width="450">Status: <TextBlock Text="{Binding Path=Status}"/></TextBlock>
<TextBlock Width="162" TextAlignment="right">
<TextBlock Text="Downloading Speed: "/>
<TextBlock Name="DownloadingSpeed" Text="{Binding Path=DownloadingSpeed}"/>
</TextBlock>
</StackPanel>
</StackPanel>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox Width="Auto"
Name="WebsiteList"
Grid.Column="1"
Grid.Row="2"
Grid.RowSpan="2"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource DownloadedWebsitesListBox}"
Margin="0,0,0,0">
</ListBox>
</Grid>
</window>
and MainWindow.xaml.cs
BindingController bc = new BindingController();
public MainWindow()
{
InitializeComponent();
bc.DownloadingSpeed = "40kb/s";
bc.WebsiteTitle = "WebsiteTitle";
bc.Status = "Downloading";
DataContext = bc;
}
and BindingController.cs
public class BindingController
{
public BindingController()
{
}
private string _WebsiteTitle;
public string WebsiteTitle
{
set { _WebsiteTitle = value; }
get { return _WebsiteTitle; }
}
private string _Status;
public string Status
{
set { _Status = value ; }
get { return _Status ; }
}
private string _DownloadStartDate;
public string DownloadStartDate
{
set { _DownloadStartDate = value; }
get { return _DownloadStartDate ; }
}
private string _DownloadingSpeed = "0 kb/s";
public string DownloadingSpeed
{
set { _DownloadingSpeed = value; }
get { return _DownloadingSpeed; }
}
}
Your problem is that you're binding a ListBox to an object that contains several properties, but really only represents a single object/state. The ListBox expects to display a list of items (i.e. IList, IBindingList, IEnumerable, ObservableCollection).
Assuming you want to display more than one download at a time, which I'm assuming given that you're using a ListBox, I would refactor the download properties into a separate class. You will also need to implement INotifyPropertyChanged on your properties so that when the values are changed, they will be shown in the UI.
public class Download : INotifyPropertyChanged
{
private string _WebsiteTitle;
public string WebsiteTitle
{
get { return _WebsiteTitle; }
set
{
if (_WebsiteTitle == value)
return;
_WebsiteTitle = value;
this.OnPropertyChanged("WebsiteTitle");
}
}
private string _Status;
public string Status
{
get { return _Status; }
set
{
if (_Status == value)
return;
_Status = value;
this.OnPropertyChanged("Status");
}
}
private string _DownloadStartDate;
public string DownloadStartDate
{
get { return _DownloadStartDate; }
set
{
if (_DownloadStartDate == value)
return;
_DownloadStartDate = value;
this.OnPropertyChanged("DownloadStartDate");
}
}
private string _DownloadingSpeed = "0 kb/s";
public string DownloadingSpeed
{
get { return _DownloadingSpeed; }
set
{
if (_DownloadingSpeed == value)
return;
_DownloadingSpeed = value;
this.OnPropertyChanged("DownloadingSpeed");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if(this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
The new BindingController:
public class BindingController
{
public BindingController()
{
this.Downloads = new ObservableCollection<Download>();
}
public ObservableCollection<Download> Downloads { get; private set; }
}
Setting up the bindings in XAML:
<ListBox Width="Auto"
Name="WebsiteList"
Grid.Column="1"
Grid.Row="2"
Grid.RowSpan="2"
ItemsSource="{Binding Downloads}"
ItemTemplate="{StaticResource DownloadedWebsitesListBox}"
Margin="0,0,0,0">
</ListBox>
Initializing the collection in MainWindow
Download download = new Download();
download.DownloadingSpeed = "40kb/s";
download.WebsiteTitle = "WebsiteTitle";
download.Status = "Downloading";
bc.Downloads.Add(download);
this.DataContext = bc;
I currently have the data for my application stored in an Azure Mobile Service SQL Database. I am pulling items from the database and displaying them in a List View. When a user clicks on an item in the list view they are then navigated to a new page that displays more details about the specific record from the database.
Main Page Code:
public class OSVersions
{
[JsonProperty(PropertyName = "id")]
public int id { get; set; }
[JsonProperty(PropertyName = "Version")]
public string Version { get; set; }
[JsonProperty(PropertyName = "Codename")]
public string Codename { get; set; }
[JsonProperty(PropertyName = "Publish")]
public bool Publish { get; set; }
[JsonProperty(PropertyName = "ReleaseDate")]
public DateTime ReleaseDate { get; set; }
[JsonProperty(PropertyName = "Changes")]
public string Changes { get; set; }
[JsonProperty(PropertyName = "Notes")]
public string Notes { get; set; }
}
public partial class OSMainVIew : PhoneApplicationPage
{
private MobileServiceCollection<OSVersions, OSVersions> items;
private IMobileServiceTable<OSVersions> osTable =
App.MobileService.GetTable<OSVersions>();
public OSMainVIew()
{
InitializeComponent();
}
private async void RefreshOSItems()
{
progressBar1.IsEnabled = true;
progressBar1.IsIndeterminate = true;
items = await osTable
.Where(OSItem => OSItem.Publish == true)
.ToCollectionAsync();
MainListBox.ItemsSource = items;
progressBar1.IsEnabled = false;
progressBar1.Visibility = System.Windows.Visibility.Collapsed;
progressBar1.IsIndeterminate = false;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
RefreshOSItems();
}
private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (MainListBox.SelectedIndex == -1)
return;
NavigationService.Navigate(new Uri("/ViewModels/OS/OSItemView.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));
MainListBox.SelectedIndex = -1;
}
}
Item Page Code:
public partial class OSItemView : PhoneApplicationPage
{
private MobileServiceCollection<OSVersions, OSVersions> items;
private IMobileServiceTable<OSVersions> osTable =
App.MobileService.GetTable<OSVersions>();
public OSItemView()
{
InitializeComponent();
if ((Application.Current as App).IsTrial)
{
//textBlock1.Text = "Change Log available in full version only!";
//textBlock2.Visibility = System.Windows.Visibility.Collapsed;
}
}
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
string selectedIndex = "";
int buildID;
int idValue;
if (NavigationContext.QueryString.TryGetValue("selectedItem", out selectedIndex))
{
//Start progressBar
progressBar1.IsEnabled = true;
progressBar1.IsIndeterminate = true;
//Convert selectedIndex -> buildID
idValue = Convert.ToInt32(selectedIndex);
buildID = idValue + 1;
/* buildID = idValue + 1 becuase on OSMainView
* Items stored in the ListBox are each even an index number
* The first number is '0'
* This is a problem because the first IDNumber in the Database is '1'
* This isn't the best way to handle this, becuase even though the id field is an auto-increamental field,
* sometimes values are skipped and rows are deleted.
*/
//Query database
items = await osTable
.Where(OSItem => OSItem.id == buildID)
.ToCollectionAsync();
MainListBox.ItemsSource = items;
//End progressBar
progressBar1.IsEnabled = false;
progressBar1.Visibility = System.Windows.Visibility.Collapsed;
progressBar1.IsIndeterminate = false;
}
}
}
Items Page XAML Code:
<Grid x:Name="ContentPanel" Margin="10,97,12,0" Grid.RowSpan="2">
<ListBox x:Name="MainListBox" Margin="10,-35,-12,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="0,0,0,0" Width="432" Height="*">
<TextBlock TextWrapping="Wrap" Text="{Binding Version}" Style=" {StaticResource PhoneTextExtraLargeStyle}"/>
<TextBlock Text="Notes" FontFamily="Segoe WP Bold" Foreground="{StaticResource PhoneAccentBrush}" Height="30" HorizontalAlignment="Left" Margin="0,1,0,0" Name="textBlock3" Padding="0" VerticalAlignment="Top" Width="444" />
<TextBlock x:Name="notesText" Text="{Binding Notes}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}" Height="180" VerticalAlignment="Top" HorizontalAlignment="Stretch" FontFamily="Segoe WP SemiLight" Margin="0" Width="455"/>
<TextBlock Text="Change Log" Height="30" HorizontalAlignment="Left" Margin="0,222,0,0" Name="textBlock1" VerticalAlignment="Top" FontFamily="Segoe WP Bold" Foreground="{StaticResource PhoneAccentBrush}" Width="444" Padding="0" />
<TextBlock Name="textBlock2" Text="{Binding Changes}" Style="{StaticResource PhoneTextNormalStyle}" TextWrapping="Wrap" Height="Auto" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" FontFamily="Segoe WP SemiLight" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
My problem occurs when MainListBox.ItemsSource = items; is executed.
The application quits without any error codes.
Any ideas?
The problem had to due with the Height of the StackPanel being set to '*'. After removing that, the problem was solved.