我正在编写一个应用程序,用于计算从0到用户指定的数字的所有素数。我的algorythm运行正常,但似乎TextBlock的高度有限:在500左右,它不会继续写入数字。我仍然可以向下滚动,但数字不再出现。 XAML:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ScrollViewer>
<StackPanel Name="stack">
<TextBlock>Calculate prime numbers from</TextBlock>
<TextBox Name="from"></TextBox>
<TextBlock>to</TextBlock>
<TextBox Name="to"></TextBox>
<Button Name="Run" Click="run">Calculate prime numbers!</Button>
<TextBlock Name="result">Hallo</TextBlock>
</StackPanel>
</ScrollViewer>
</Grid>
C#:
public void run(object sender, RoutedEventArgs e)
{
int min; int.TryParse(from.Text, out min);
int max; int.TryParse(to.Text, out max);
List<int> numbers = new List<int>();
for (int i = min; i <= max; i++)
{
numbers.Add(i);
}
int checknext = 2;
while (checknext < Math.Sqrt(max))
{
for (int i = numbers.Count - 1; i >= 0; i--)
{
if (!(numbers[i] == checknext))
{
if (numbers[i] % checknext == 0)
numbers.RemoveAt(i);
}
}
checknext++;
}
result.Text = "";
result.MaxHeight = double.MaxValue;
for (int i = 0; i < numbers.Count; i++)
{
result.Text += numbers[i].ToString() + "\n";
}
}
答案 0 :(得分:1)
试试这种方式
XAML代码
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<ScrollViewer>
<StackPanel Name="stack">
<TextBlock>Calculate prime numbers from</TextBlock>
<TextBox Name="from"></TextBox>
<TextBlock>to</TextBlock>
<TextBox Name="to"></TextBox>
<Button Name="Run" Click="run">Calculate prime numbers!</Button>
<ListBox x:Name="lstbx" Visibility="Visible" Height="300" Margin="0" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<ListBoxItem>
<StackPanel Name="stkpnlMsg" Margin="0">
<Grid VerticalAlignment="Top" HorizontalAlignment="Left" Width="300" Height="auto">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Text="{Binding number}" Padding ="0,0,0,10" FontSize="20" FontWeight="Normal" ></TextBlock>
</Grid>
</StackPanel>
</ListBoxItem>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</ScrollViewer>
</Grid>
C#代码
第1步:声明此列表
public List<BindData> dataSource;
第2步:
public class BindData
{
public string number { get; set; }
}
第3步:
public void run(object sender, RoutedEventArgs e)
{
dataSource = new List<BindData>();
dataSource.Clear();
int min; int.TryParse(from.Text, out min);
int max; int.TryParse(to.Text, out max);
List<int> numbers = new List<int>();
for (int i = min; i <= max; i++)
{
numbers.Add(i);
}
int checknext = 2;
while (checknext < Math.Sqrt(max))
{
for (int i = numbers.Count - 1; i >= 0; i--)
{
if (!(numbers[i] == checknext))
{
if (numbers[i] % checknext == 0)
numbers.RemoveAt(i);
}
}
checknext++;
}
for (int i = 0; i < numbers.Count; i++)
{
dataSource.Add(new BindData() { number = numbers[i].ToString() });
}
this.lstbx.ItemsSource = dataSource;
}